I want to use AES to encrypt a password in Objective-C, and then decrypt it in PHP, but I have two problems.
- I encrypt the password, but it's an
NSData
object, so I encode it with base64, but when I decode in PHP, the result is nil
. So I can't decrypt it. - I can encrypt and decrypt the password in Objective-C, so it is the PHP that is the problem, but when I encrypt with AES and then encode with base64, the results are not the same.
Here is my code:
PHP:
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$key = "a16byteslongkey!";
$plaintext = "iphone";
$ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $plaintext, MCRYPT_MODE_ECB, $iv);
$ciphertext = base64_encode($ciphertext);
echo "ciphertext: ".$ciphertext."<br/>";
$ciphertext = base64_decode($ciphertext);
$plaintext = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $ciphertext, MCRYPT_MODE_ECB, $iv);
echo "plaintext: ".$plaintext."<br/>";
output:
ciphertext: SXNepKfh0IrlDDdkq4EdmQ==
plaintext: iphone
Objective-C: (Get the full source code here: https://gist.github.com/838614)
NSString *key = @"a16byteslongkey!";
NSString *plaintext = @"iphone";
NSString *ciphertext = [plaintext AES256EncryptWithKey: key];
NSLog(@"ciphertext: %@", ciphertext);
plaintext = [ciphertext AES256DecryptWithKey: key];
NSLog(@"plaintext: %@", plaintext);
output:
ciphertext: D19l3gsgXJlrLl7B2oCT6g==
plaintext: iphone
i replace kCCKeySizeAES256 with kCCKeySizeAES128, and replace "kCCOptionPKCS7Padding" with "kCCOptionPKCS7Padding | kCCOptionECBMode",
base64_encode
-ing the resulting string in PHP but only converting it to UTF8 in Obj-C. Obviously, the results will be different. – Aleks G Aug 23 '11 at 17:43