我目前在 iOS 中加密并在 PHP 中解密。如果我正在加密/解密的字符串长度小于 16 个字符,它工作正常。
要加密的 iOS 代码:
- (NSData *)AES128Encrypt:(NSData *)this
{
// ‘key’ should be 16 bytes for AES128
char keyPtr[kCCKeySizeAES128 + 1]; // room for terminator (unused)
bzero( keyPtr, sizeof( keyPtr ) ); // fill with zeroes (for padding)
NSString *key = @"1234567890123456";
// fetch key data
[key getCString:keyPtr maxLength:sizeof( keyPtr ) encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [this length];
//See the doc: For block ciphers, the output size will always be less than or
//equal to the input size plus the size of one block.
//That’s why we need to add the size of one block here
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc( bufferSize );
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt( kCCEncrypt, kCCAlgorithmAES128, kCCOptionECBMode | kCCOptionPKCS7Padding,
keyPtr, kCCKeySizeAES128,
NULL /* initialization vector (optional) */,
[this bytes], dataLength, /* input */
buffer, bufferSize, /* output */
&numBytesEncrypted );
if( cryptStatus == kCCSuccess )
{
//the returned NSData takes ownership of the buffer and will free it on deallocation
return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
}
free( buffer ); //free the buffer
return nil;
}
PHP代码解密:
function decryptThis($key, $pass)
{
$base64encoded_ciphertext = $pass;
$res_non = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $base64encoded_ciphertext, MCRYPT_MODE_CBC);
$decrypted = $res_non;
$dec_s2 = strlen($decrypted);
$padding = ord($decrypted[$dec_s2-1]);
$decrypted = substr($decrypted, 0, -$padding);
return $decrypted;
}
如果解密的字符串超过 16 个字符,PHP 只返回@"\n\n"。但是,像 ' what '这样的短字符串会被正确解密,并且 PHP 返回@"what\n\n"。这里发生了什么?我希望能够解密 500 多个字符长的字符串。