下面的方法在iOS 7上的运行结果与iOS 8/9不同。
+ (NSData *)decryptData:(NSData *)data key:(NSData *)key iv:(NSData *)iv;
{
NSData *result = nil;
// setup key
unsigned char cKey[FBENCRYPT_KEY_SIZE];
bzero(cKey, sizeof(cKey));
[key getBytes:cKey length:FBENCRYPT_KEY_SIZE];
// setup iv
char cIv[FBENCRYPT_BLOCK_SIZE];
bzero(cIv, FBENCRYPT_BLOCK_SIZE);
if (iv) {
[iv getBytes:cIv length:FBENCRYPT_BLOCK_SIZE];
}
// setup output buffer
size_t bufferSize = [data length] + FBENCRYPT_BLOCK_SIZE;
void *buffer = malloc(bufferSize);
// do decrypt
size_t decryptedSize = 0;
CCCryptorStatus cryptStatus =
CCCrypt(kCCDecrypt, FBENCRYPT_ALGORITHM, kCCOptionPKCS7Padding, cKey,
FBENCRYPT_KEY_SIZE, cIv, [data bytes], [data length], buffer,
bufferSize, &decryptedSize);
if (cryptStatus == kCCSuccess) {
result = [NSData dataWithBytesNoCopy:buffer length:decryptedSize];
} else {
free(buffer);
NSLog(@"[ERROR] failed to decrypt| CCCryptoStatus: %d", cryptStatus);
}
return result;
}
iOS 7/8/9都支持加密,但在iOS 7上解密结果为nil。
执行后decryptedSize
为0,buffer
元素仍然为0。
以下是一些定义:
#define FBENCRYPT_ALGORITHM kCCAlgorithmAES128
#define FBENCRYPT_BLOCK_SIZE kCCBlockSizeAES128
#define FBENCRYPT_KEY_SIZE kCCKeySizeAES256
我已经阅读了关于类似 CCCrypt()
问题的 SO 回答。尝试了以下几种方法:
- 将
cKey
的长度增加 1。 - 将
cKey
的长度增加到FBENCRYPT_KEY_SIZE * 2 + 1
。 - 将
cKey
的第一个字节设置为 0(有人说当从 NSString 获取密钥字节时,iOS 6 会这样做)。
以上任何一种方法都无法解决问题。
我提供了一些调用该方法时的示例数据。
传递给 decryptData
的三个参数分别是:
- data:
ea1e6896 b5731f40 1d560a18 f0729fa6
- key:
17c76e90 9a6fef8d b1fd45fa 2de18db0 d2236264 db6c8a60 125599ec 2dfb5614
,AES256 的密钥长度为 256 位 - iv:
41463531 38453234 44333835 42463636
,16 字节,与块大小相同
期望结果(并且在 iOS8/9 上实际结果)是 248e51af 66bf85d3 00003ab6 fe3c0000
。