I am using the CommonCrypto CCCryptorCreate to decrypt a message. I am using a password and an IV but it always returns nil.
If I use the CCCryptorCreate to decrypt, but don't use an IV on during encryption on the RUBY side and don't use the IV on the obj-c decrypt side then decryption works perfectly and I can see the message.
But if I use an IV on the RUBY and IV on the obj-c side decryption ends with a nil message object.
I am using this Encrypt in Objective-C / Decrypt in Ruby using anything
OBJ-C method:
- (NSData *) decryptedDataUsingAlgorithm: (CCAlgorithm) algorithm
key: (id) key // data or string
initializationVector: (id) iv // data or string
options: (CCOptions) options
error: (CCCryptorStatus *) error
{
CCCryptorRef cryptor = NULL;
CCCryptorStatus status = kCCSuccess;
NSParameterAssert([key isKindOfClass: [NSData class]] || [key isKindOfClass: [NSString class]]);
NSParameterAssert(iv == nil || [iv isKindOfClass: [NSData class]] || [iv isKindOfClass: [NSString class]]);
NSMutableData * keyData, * ivData;
if ( [key isKindOfClass: [NSData class]] )
keyData = (NSMutableData *) [key mutableCopy];
else
keyData = [[key dataUsingEncoding: NSUTF8StringEncoding] mutableCopy];
if ( [iv isKindOfClass: [NSString class]] )
ivData = [[iv dataUsingEncoding: NSUTF8StringEncoding] mutableCopy];
else
ivData = (NSMutableData *) [iv mutableCopy]; // data or nil
#if !__has_feature(objc_arc)
[keyData autorelease];
[ivData autorelease];
#endif
// ensure correct lengths for key and iv data, based on algorithms
FixKeyLengths( algorithm, keyData, ivData );
status = CCCryptorCreate( kCCDecrypt, algorithm, options,
[keyData bytes], [keyData length], [ivData bytes],
&cryptor );
if ( status != kCCSuccess )
{
if ( error != NULL )
*error = status;
return ( nil );
}
NSData * result = [self _runCryptor: cryptor result: &status];
if ( (result == nil) && (error != NULL) )
*error = status;
CCCryptorRelease( cryptor );
return ( result );
}
=== DOES NOT WORK ====
NSData * result = [self decryptedDataUsingAlgorithm: kCCAlgorithmAES128
key: [[password dataUsingEncoding:NSUTF8StringEncoding] SHA256Hash]
initializationVector: [anIV dataUsingEncoding:NSUTF8StringEncoding]
options: kCCOptionPKCS7Padding
error: &status];
=== DOES WORK ===
NSData * result = [self decryptedDataUsingAlgorithm: kCCAlgorithmAES128
key: [[password dataUsingEncoding:NSUTF8StringEncoding] SHA256Hash]
initializationVector: nil
options: kCCOptionPKCS7Padding
error: &status];