我目前正在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个字符的字符串。
答案 0 :(得分:0)
您在iOS中使用ECB模式,在PHP上使用CBC。 PHP还没有检测到不正确的填充,所以如果(不正确的)填充明文的最后一个字节值很高,它可能会生成一个空字符串。