iOS CCCrypt kCCDecrypt使用kCCAlgorithmAES128

时间:2012-05-08 17:33:50

标签: ios commoncrypto

以下是代码:

- (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中尝试不使用填充,如此处所述Anyone else having trouble with iOS 5 encryption? 我没有得到错误。但有时kCCDecrypt之后的数据长度与kCCEncrypt之前的原始数据长度不同。我认为这是因为原始数据长度不会乘以编码块大小。

其他人有这个麻烦吗?

1 个答案:

答案 0 :(得分:1)

你不能只是抛出填充物。保持填充,一切都会好起来。

另请参阅:Encrypting 16 bytes of UTF8 with SecKeyWrapper breaks (ccStatus == -4304)