使用 ECB 模式(这是玩具加密)和 PKCS7 填充使用 AES128 加密的密文,以下代码块导致在 iOS 8 下恢复完整的明文。
在 iOS 7 下运行相同的代码块会生成正确的明文,但会被截断。为什么是这样?
#import "NSData+AESCrypt.h" // <-- a category with the below function
#import <CommonCrypto/CommonCryptor.h>
- (NSData *)AES128Operation:(CCOperation)operation key:(NSString *)key iv:(NSString *)iv
{
char keyPtr[kCCKeySizeAES128 + 1];
bzero(keyPtr, sizeof(keyPtr));
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
char ivPtr[kCCBlockSizeAES128 + 1];
bzero(ivPtr, sizeof(ivPtr));
if (iv) {
[iv getCString:ivPtr maxLength:sizeof(ivPtr) encoding:NSUTF8StringEncoding];
}
NSUInteger dataLength = [self length];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(operation,
kCCAlgorithmAES128,
kCCOptionPKCS7Padding | kCCOptionECBMode,
keyPtr,
kCCBlockSizeAES128,
ivPtr,
[self bytes],
dataLength,
buffer,
bufferSize,
&numBytesEncrypted);
if (cryptStatus == kCCSuccess) {
return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
}
free(buffer);
return nil;
}
我在下面添加了一个带有结果的独立测试工具。
测试线束:
NSString *key = @"1234567890ABCDEF";
NSString *ciphertext = @"I9JIk5BskZMZKJFB/EAs+N2AYzkVR15DoBbUL7cBydBkWGlujVnzRHvBNvSVbcKh";
NSData *encData = [[NSData alloc]initWithBase64EncodedString:ciphertext options:0];
NSData *plainData = [encData AES128Operation:kCCDecrypt key:key iv:nil];
NSString *plaintext = [NSString stringWithUTF8String:[plainData bytes]];
DLog(@"key: %@\nciphertext: %@\nplaintext: %@", key, ciphertext, plaintext);
iOS 8 结果:
key: 1234567890ABCDEF
ciphertext: I9JIk5BskZMZKJFB/EAs+N2AYzkVR15DoBbUL7cBydBkWGlujVnzRHvBNvSVbcKh
plaintext: the quick brown fox jumped over the fence
iOS 7 结果:
key: 1234567890ABCDEF
ciphertext: I9JIk5BskZMZKJFB/EAs+N2AYzkVR15DoBbUL7cBydBkWGlujVnzRHvBNvSVbcKh
plaintext: the quick brown fox jumped over 0
和随后的结果:
plaintext: the quick brown fox jumped over
plaintext: the quick brown fox jumped over *
更新:谜语:当我改变时
kCCOptionPKCS7Padding | kCCOptionECBMode ⇒ kCCOptionECBMode
iOS 7 中的结果符合预期。为什么是这样??我知道字节数是块对齐的,因为密文是用 PKCS7 填充填充的,所以这是有道理的,但为什么设置kCCOptionPKCS7Padding | kCCOptionECBMode
只导致 iOS 7 中的截断行为?
编辑:上面的测试密文是从这个网站生成的,并且在以下函数中独立使用 PHP 的 mcrypt 和手动 PKCS7 填充:
function encryptAES128WithPKCS7($message, $key)
{
if (mb_strlen($key, '8bit') !== 16) {
throw new Exception("Needs a 128-bit key!");
}
// Add PKCS7 Padding
$block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128);
$pad = $block - (mb_strlen($message, '8bit') % $block);
$message .= str_repeat(chr($pad), $pad);
$ciphertext = mcrypt_encrypt(
MCRYPT_RIJNDAEL_128,
$key,
$message,
MCRYPT_MODE_ECB
);
return $ciphertext;
}
// Demonstration encryption
echo base64_encode(encryptAES128WithPKCS7("the quick brown fox jumped over the fence", "1234567890ABCDEF"));
出去:
I9JIk5BskZMZKJFB/EAs+N2AYzkVR15DoBbUL7cBydBkWGlujVnzRHvBNvSVbcKh
更新:正确的 PKCS#7-padded 密文将是
I9JIk5BskZMZKJFB/EAs+N2AYzkVR15DoBbUL7cBydA6aE5a3JrRst9Gn3sb3heC
这就是为什么不是。