I am working on incorporating encryption for data stored in my application. I have gotten pretty far in that I am encrypting and decrypting data, my problem is that I cannot seem to force an obvious decryption error when the wrong key is used. My decrypt function:
+ (NSData *)decryptedDataForData:(NSData *)data
password:(NSString *)password
iv:(NSData *)iv
salt:(NSData *)salt
error:(NSError **)error {
NSAssert(iv, @"IV must not be NULL");
NSAssert(salt, @"salt must not be NULL");
NSData *key = [self AESKeyForPassword:password salt:salt];
size_t outLength;
NSMutableData *
decryptedData = [NSMutableData dataWithLength:data.length];
CCCryptorStatus
result = CCCrypt(kCCDecrypt,
kAlgorithm,
kCCOptionPKCS7Padding,
key.bytes,
key.length,
iv.bytes,
data.bytes,
data.length,
decryptedData.mutableBytes,
decryptedData.length,
&outLength);
if (result == kCCSuccess) {
decryptedData.length = outLength;
}
else {
if (error) {
*error = [NSError errorWithDomain:kRNCryptManagerErrorDomain
code:result
userInfo:nil];
}
return nil;
}
return decryptedData;
}
This is taken from http://robnapier.net/aes-commoncrypto for reference.
According to the CCCrypt documentation, I should receive a kCCDecodeError if my data does not properly decrypt, so I assume that the decrypt operation was successful, just gave garbage data due to the wrong key.
So, what is the best practice for determining if the correct key was used to decrypt the data?