我想在 Objective-C 中使用 AES 加密密码,然后在 PHP 中解密,但我有两个问题。
- 我加密了密码,但它是一个
NSData
对象,所以我用 base64 对它进行编码,但是当我用 PHP 解码时,结果是nil
。所以我无法解密它。 - 我可以在 Objective-C 中加密和解密密码,所以是 PHP 的问题,但是当我用 AES 加密然后用 base64 编码时,结果不一样。
这是我的代码:
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/>";
输出:
ciphertext: SXNepKfh0IrlDDdkq4EdmQ==
plaintext: iphone
Objective-C:(在这里获取完整的源代码: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);
输出:
ciphertext: D19l3gsgXJlrLl7B2oCT6g==
plaintext: iphone
我将 kCCKeySizeAES256 替换为 kCCKeySizeAES128,将“kCCOptionPKCS7Padding”替换为“kCCOptionPKCS7Padding | kCCOptionECBMode”,
最佳答案
我已经解决了这个问题。
- 不要更改 https://gist.github.com/838614 中的代码
- key 应为 32 字节。
- 加密的结果不一样,但解密后的结果是一样的。
objective-c :
NSString *key = @"a16byteslongkey!a16byteslongkey!";
NSString *plaintext = @"iphone";
NSString *ciphertext = [plaintext AES256EncryptWithKey: key];
NSLog(@"ciphertext: %@", ciphertext);
plaintext = [ciphertext AES256DecryptWithKey: key];
NSLog(@"plaintext: %@", plaintext);
输出:
ciphertext: I3chV+E2XUHeLCcJAhBaJQ==
plaintext: iphone
PHP:
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$key = 'a16byteslongkey!a16byteslongkey!';
$plaintext = "iphone";
$ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $plaintext, MCRYPT_MODE_ECB);
$base64encoded_ciphertext = base64_encode($ciphertext);
echo "ciphertext: ".$base64encoded_ciphertext."<br/>";
$plaintext = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, base64_decode($base64encoded_ciphertext), MCRYPT_MODE_ECB);
echo "plaintext: ".$plaintext."<br/>";
$base64encoded_ciphertext = "I3chV+E2XUHeLCcJAhBaJQ==";
$plaintext = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, base64_decode($base64encoded_ciphertext), MCRYPT_MODE_ECB);
echo "plaintext: ".trim($plaintext);
输出:
ciphertext: kUr+YsYtb3Uy34li/GPcjg==
plaintext: iphone
plaintext: iphone
关于php - 使用AES用Objective-C加密用PHP解密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7163690/