这是代码:
- (NSData *) doCipher: (NSData *) plainData key: (NSData *) symmetricKey context: (CCOperation) encryptOrDecrypt padding: (CCOptions *) pkcs7
{
// Initialization vector; dummy in this case 0's.
uint8_t iv[kChosenCipherBlockSize];
bzero((void *) iv, (size_t) sizeof(iv));
// We don't want to toss padding on if we don't need to
if (encryptOrDecrypt == kCCEncrypt)
{
if (*pkcs7 != kCCOptionECBMode)
{
if ((plainData.length % kChosenCipherBlockSize) == 0)
*pkcs7 = 0x0000;
else
*pkcs7 = kCCOptionPKCS7Padding;
}
}
else if (encryptOrDecrypt == kCCDecrypt)
{
*pkcs7 = 0x0000;
}
else
{
DLog(@"Invalid CCOperation parameter [%d] for cipher context.", *pkcs7);
return nil;
}
// Actually perform the encryption or decryption.
NSMutableData *dataOut = [NSMutableData dataWithLength: plainData.length + kChosenCipherBlockSize];
size_t movedBytes = 0;
CCCryptorStatus ccStatus = CCCrypt(encryptOrDecrypt,
kCCAlgorithmAES128,
*pkcs7,
symmetricKey.bytes,
kChosenCipherKeySize,
iv,
[plainData bytes],
[plainData length],
[dataOut mutableBytes],
[dataOut length],
&movedBytes
);
if (ccStatus == noErr)
{
dataOut.length = movedBytes;
}
else
{
DLog(@"Problem with encipherment ccStatus == %d", ccStatus);
return nil;
}
return dataOut;
}
当我在 kCCDecrypt 上使用 kCCOptionPKCS7Padding 时,有时我会收到错误代码 4304。我尝试在 kCCDecrypt 时不使用填充,如此处所述还有其他人在使用 iOS 5 加密时遇到问题吗? 我没有得到错误。但有时 kCCDecrypt 后的数据长度与 kCCEncrypt 前的原始数据长度不同。我认为这是因为原始数据长度没有乘以编码块大小。
其他人有这个烦恼吗?