Reputation: 33
Here is the code:
- (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;
}
When I using kCCOptionPKCS7Padding on kCCDecrypt sometimes I get error code 4304. I try not using padding when kCCDecrypt as described here Anyone else having trouble with iOS 5 encryption? and I don't get the error. But sometimes the data length after kCCDecrypt is not the same as original data length before kCCEncrypt. I think this is because original data length is not multiplied by encoding block size.
Anyone else have this trouble?
Upvotes: 2
Views: 4738
Reputation: 93968
You cannot just toss out padding. Leave padding on and everything will be alright.
See also: Encrypting 16 bytes of UTF8 with SecKeyWrapper breaks (ccStatus == -4304)
Upvotes: 3