问题
I have an issue with HTTP POST requests encrypting & decrypting.
I have an OS X Application written in Objective-C which sends encrypted (CocoaSecurity) HTTP POST request to server:
- (NSString *)secure
{
NSData* key = [@"9eab87dc72b927c9" dataUsingEncoding:NSASCIIStringEncoding];
NSData* iv = [@"d6f8f85911c4d8d1" dataUsingEncoding:NSASCIIStringEncoding];
CocoaSecurityResult *result = [CocoaSecurity aesEncrypt:@"a" key:key iv:iv];
return result.hexLower;
}
and I am getting encryption
5219abd6c1439dc832ab512dae8cce80
Also I have a WEB Application written in PHP which decrypts sent request
protected function processEncrypt()
{
if ($this->input) {
$crypt = mcrypt_module_open($this->algorithm, '', $this->mode, $this->encryptIv);
mcrypt_generic_init($crypt, $this->encryptKey, $this->encryptIv);
$this->input = mcrypt_generic($crypt, $this->input);
mcrypt_generic_deinit($crypt);
mcrypt_module_close($crypt);
if ($this->template == 'hex') {
$this->input = bin2hex($this->input);
} elseif ($this->template == 'base64') {
$this->input = base64_encode($this->input);
}
}
}
The encrypted message, at the end of request handling, is totally different from the decrypted one.
I am getting encryption
10967675e5cf70878ee063a73f2a8394
Until now I have found out, that this might be a PKCS#7
padding issue (PHP mcrypt library has null padding). I have tried to remove padding by changing CocoaSecurity.m
source and replacing kCCOptionPKCS7Padding
value to 0
. After this replacement, CocoaSecurity
raises exception Encrypt Error!
triggered by kCCAlignmentError
...
Could anyone tell me, where is the problem?
回答1:
Note that CocoaSecurity uses standard PKCS#7 padding (kCCOptionPKCS7Padding
) but mcrypt uses non-standard/insecure null padding. You will need to remove the PKCS#7 padding in your php code. You can use the this code:
Add PKCS#7 padding (php):
$pad = $block - (strlen($str) % $block);
$str .= str_repeat(chr($pad), $pad);
Remove PKCS#7 padding (php):
$len = strlen($str);
$pad = ord($str[$len-1]);
$str = $strsubstr($str, 0, $len - $pad);
See this SO answer for detailed information.
来源:https://stackoverflow.com/questions/32138354/http-request-encrypt-decrypt-failure-with-php-objective-c