AES256 decryption issue in Objective-c - objective-c

I am trying to use the following snippet to decrypt file, which was encrypted with 32 byte key. So when I am trying to encrypt file data, everything is going ok. But when I am trying do decrypt, program even don't pass the condition if (cryptStatus == kCCSuccess) in CryptoExtensions.m. I am really tired figuring out a problem. I was trying to use Base64 decoding, but my file is saved in UTF8 encoding, so I have no problems when I just put it's content in log from NSData:
NSData *fileData = [[[NSData alloc] initWithContentsOfFile:destPath] autorelease];
NSLog(#"File data:%#",[[NSString alloc] initWithData:fileData encoding:NSUTF8StringEncoding]);
But when I am trying to decrypt it, I am getting nil from CryptoExtensions method:
NSData *aesResponse = [fileData AES256DecryptWithKey:#"4QXcCZlgRAIchiaqkMVpF3nkpARmdL3z"];
NSLog(#"AES:%#",[[NSString alloc] initWithData:aesResponse encoding:NSUTF8StringEncoding]);
This is contents of crypto snippet:
CryptoExtensions.h
#import <Foundation/Foundation.h>
#interface NSData (CryptoExtensions)
- (NSData*)AES256EncryptWithKey:(NSString*)key;
- (NSData*)AES256DecryptWithKey:(NSString*)key;
#end
CryptoExtensions.m
#import "CryptoExtensions.h"
#import <CommonCrypto/CommonCryptor.h>
#implementation NSData (CryptoExtensions)
- (NSData*)AES256EncryptWithKey:(NSString*)key {
// 'key' should be 32 bytes for AES256, will be null-padded otherwise
char keyPtr[kCCKeySizeAES256 + 1]; // room for terminator (unused)
bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding)
// fetch key data
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [self length];
//See the doc: For block ciphers, the output size will always be less than or
//equal to the input size plus the size of one block.
//That's why we need to add the size of one block here
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void* buffer = malloc(bufferSize);
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
keyPtr, kCCKeySizeAES256,
NULL /* initialization vector (optional) */,
[self bytes], dataLength, /* input */
buffer, bufferSize, /* output */
&numBytesEncrypted);
if (cryptStatus == kCCSuccess)
{
//the returned NSData takes ownership of the buffer and will free it on deallocation
return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
}
free(buffer); //free the buffer;
return nil;
}
- (NSData*)AES256DecryptWithKey:(NSString*)key {
// 'key' should be 32 bytes for AES256, will be null-padded otherwise
char keyPtr[kCCKeySizeAES256 + 1]; // room for terminator (unused)
bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding)
// fetch key data
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [self length];
//See the doc: For block ciphers, the output size will always be less than or
//equal to the input size plus the size of one block.
//That's why we need to add the size of one block here
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void* buffer = malloc(bufferSize);
size_t numBytesDecrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
keyPtr, kCCKeySizeAES256,
NULL /* initialization vector (optional) */,
[self bytes], dataLength, /* input */
buffer, bufferSize, /* output */
&numBytesDecrypted);
if (cryptStatus == kCCSuccess)
{
//the returned NSData takes ownership of the buffer and will free it on deallocation
return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
}
free(buffer); //free the buffer;
return nil;
}
#end

This code has significant security issues. It incorrectly constructs the AES key, drastically reducing the keyspace and has no IV, creating problems for the first block. I strongly recommend against this code.
I'm most of the way through developing a replacement for this commonly-used snippet. See https://github.com/rnapier/RNCryptor. If it doesn't work for you out of the box, let me know. I'm trying to make it easy enough to use for all the common cases that people will stop using AES256EncryptWithKey.
For a much longer discussion about the problems with this code, see Properly encrypting with AES with CommonCrypto. I love that someone wrapped up AES encryption into an easy to use category. I just wish that it hadn't had so many security issues.
EDIT: Coming back to your actual question, did you use AES256EncryptWithKey to encrypt this data? If not, then the specific format is likely radically different. Almost every AES encryption implementation uses a different approach in generating its input parameters and then generating its output (most don't document this well, either). You have to match the parameters and format. For example, you can't use AES256EncryptWithKey to decrypt something generated with openssl enc.

Related

CCCrypt not work on xcode 5 for ios 7

I try to use CCCrypt method, but it has different result from XCode4 and XCode5
- (NSData *)AES256DecryptWithKey:(NSString *)key
{
// 'key' should be 32 bytes for AES256, will be null-padded otherwise
char keyPtr[kCCKeySizeAES256+1]; // room for terminator (unused)
bzero( keyPtr, sizeof( keyPtr ) ); // fill with zeroes (for padding)
// fetch key data
[key getCString:keyPtr maxLength:sizeof( keyPtr ) encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [self length];
//See the doc: For block ciphers, the output size will always be less than or
//equal to the input size plus the size of one block.
//That's why we need to add the size of one block here
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc( bufferSize );
size_t numBytesDecrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt( kCCDecrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
keyPtr, kCCKeySizeAES256,
NULL /* initialization vector (optional) */,
[self bytes], dataLength, /* input */
buffer, bufferSize, /* output */
&numBytesDecrypted );
if( cryptStatus == kCCSuccess )
{
//the returned NSData takes ownership of the buffer and will free it on deallocation
return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
}
free( buffer ); //free the buffer
return nil;
}
when I call this method with this lines ... different result
NSString *password = #"E7VRcIXn8yb2Ab+t/in9UzRof6vOpOYebgKbpt1GOcfDF8rpc5nZXngx1G8QfbDqsVrwZw26609GVwruUBrOirCI/WUT8U87fbD6lSy/zPwFIYC113LgXIEylYgzIWO4";
NSString *pwd = [password AES256DecryptWithKey: #"abcd"];
if (pwd) {
NSString *checkKey = #"0sSBf7Ncyov+uzvDikOBiA==";
NSString *uncryptChk = [checkKey AES256DecryptWithKey: pwd];
In XCode4 the result is "abcd", whereas in XCode5 the result is "".
Ran into this issue myself. it seems they fixed a bug from iOS6 to iOS7 regarding [NSString keyCString:maxLength:encoding] The old method on iOS6 would cut off part of the buffer to fill the keyPtr.
An easy fix would be to increase the keyPTr size to
char keyPtr = kCCKeySizeAES256 * 2 + 1;
However keep in mind that when you upgrade apps form 6 to 7, while it should work. the keyCString truncates the length to match the size of keyPtr. and replaces the first character with 0. So to make sure that it works on both platforms. Add the above code, and set keyPtr[0] = 0;

AES128 decryption with NSData as key

I'm having a hard time decrypting NSData with NSData key. While decrypting with NSString everything works fine, yet with data as key, the method returns null NSData, eventhough status is ok, and key is also correct for that data. Here is my call
NSData *decrypted = [AES AES128DecryptWithKey:data key:mute];
NSLog(#"DECRYPTED >> %#", decrypted);
And my method
+ (NSData*)AES128DecryptWithKey:(NSData*) data key:(NSData*)key {
NSUInteger dataLength = [data length];
NSLog(#"trying to decrypt >> %# with key >> %#", data, key );
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void* buffer = malloc(bufferSize);
size_t numBytesDecrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
[key bytes], kCCKeySizeAES128,
NULL /* initialization vector (optional) */,
[data bytes], dataLength, /* input */
buffer, bufferSize, /* output */
&numBytesDecrypted);
NSLog(#"cryptstatus %d", cryptStatus);
if (cryptStatus == kCCSuccess)
{
return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
}
free(buffer); //free the buffer;
return nil;
}
NSLog output:
trying to decrypt >> <152f052e 79436003 7a9c1a59 3b82f1c4>
with key >> <1b510e76 ac0000a1 027af26a e25ad24a>
cryptstatus 0
DECRYPTED >> <>
Looked into RNEncryptor, yet it only has aes256, while i need 128. Any ideas?
It could be that the single byte block only contains padding bytes. In that case zero bytes would be the expected outcome.
This is not the case for your ciphertext, in your case no padding was applied during encryption, so you will get a failure when you try and unpad the data.

CCCrypt encrypted with ios5 can't be decrypted with ios6

My cocos2d game saves data using CCCrypt() encryption. I use the mac address as the encryption key. The save file encrypted in IOS5 can't decrypt with the same mac address in IOS6. That means that a user who updated their game will lose all their data!
Is there any way to decrypt the old file?
Here's code:
#implementation NSData (AESAdditions)
- (NSData*)AES256EncryptWithKey:(NSString*)key {
// 'key' should be 32 bytes for AES256, will be null-padded otherwise
char keyPtr[kCCKeySizeAES256 + 1]; // room for terminator (unused)
bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding)
// fetch key data
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [self length];
//See the doc: For block ciphers, the output size will always be less than or
//equal to the input size plus the size of one block.
//That's why we need to add the size of one block here
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void* buffer = malloc(bufferSize);
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
keyPtr, kCCKeySizeAES256,
NULL /* initialization vector (optional) */,
[self bytes], dataLength, /* input */
buffer, bufferSize, /* output */
&numBytesEncrypted);
if (cryptStatus == kCCSuccess)
{
//the returned NSData takes ownership of the buffer and will free it on deallocation
return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
}
free(buffer); //free the buffer;
return nil;
}
- (NSData *)AES256DecryptWithKey:(NSString *)key {
// 'key' should be 32 bytes for AES256, will be null-padded otherwise
char keyPtr[kCCKeySizeAES256+1]; // room for terminator (unused)
bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding)
// fetch key data
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [self length];
//See the doc: For block ciphers, the output size will always be less than or
//equal to the input size plus the size of one block.
//That's why we need to add the size of one block here
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
size_t numBytesDecrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
keyPtr, kCCKeySizeAES256,
NULL /* initialization vector (optional) */,
[self bytes], dataLength, /* input */
buffer, bufferSize, /* output */
&numBytesDecrypted);
if (cryptStatus == kCCSuccess) {
//the returned NSData takes ownership of the buffer and will free it on deallocation
return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
}
free(buffer); //free the buffer;
return nil;
}
#end
You'd need to give details on how you implemented your encryption, particularly what options you used.
The most common cause of failed decrypts on iOS 6 in my experience is the CTR bug that they changed/fixed. In iOS 5, there was the option kCCModeOptionCTR_LE which was a lie. It actually encrypted with kCCModeOptionCTR_BE. In iOS 6, they fixed this, and if you try to used kCCModeOptionCTR_LE you'll get an "unimplemented" error. But CCCrypt() doesn't generally use CTR mode, so I don't know if this applies.
Ok, I found the solution.
Key point here:
I add two methods to NSData to encrypt and decrypt with code based IOS5 lib.
#implementation NSData (AESAdditions)
-(NSData*)AES256EncryptWithKey:(NSString*)key;
-(NSData *)AES256DecryptWithKey:(NSString *)key
Now in IOS6 lib,NSData might be changed,so two methods worked different,it can't decrypt the file encrypt in IOS5.
In my code based IOS6,I wrote methods in my class.
like this:
- (NSData*)AES256EncryptWithKey:(NSString*)key data:(NSData *)data;
- (NSData *)AES256DecryptWithKey:(NSString *)key data:(NSData *)data;
the code work well same as in IOS5.

OSX AES Encryption is not working

In my application, i need to encrypt the file before sending it over the network and on the other end, it will get decrypt, This is my code,
-(void)doEncryptTest:(NSString *)pFileName{
// read the NSData;
NSStringEncoding encoding =NSUTF8StringEncoding;
NSString *pFileContent = #"xaaaaaaxxaaaaaax";
NSString *pKey = #"01234567012345670123456701234567";
NSData *pData = [pFileContent dataUsingEncoding:encoding];
NSData *pEncryptedData = [pData AES256EncryptWithKey:pKey];
NSData *decrypted=[pEncryptedData AES256DecryptWithKey:pKey Data:pEncryptedData];
NSString* pDecryptedDataStr = [[NSString alloc] initWithData:decrypted
encoding:encoding];
}
This is working fine , only and only if Data size is 16 byte, in real time case, when i sent the file of size 151186 bytes, size of [pEncryptedData] is 15200 , and in fact size of decrypted data is same as original data,
But pDecryptedDataStr is blank, any guess what is going wrong,
please refer below, Encryption and decryption function,
int keySize = kCCKeySizeAES256;
int padding = kCCOptionPKCS7Padding;
char ivKey[16]={0,0,0,0,
0,0,0,0,
0,0,0,0,
0,0,0,0};
//////////////*Encryption*///////////////////
- (NSData *)AES256EncryptWithKey:(NSString *)key{
// 'key' should be 32 bytes for AES256, will be null-padded otherwise
char keyPtr[keySize + 1]; // room for terminator (unused)
bzero( keyPtr, sizeof( keyPtr ) ); // fill with zeroes (for padding)
// fetch key data
[key getCString:keyPtr maxLength:sizeof( keyPtr ) encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [self length];
//See the doc: For block ciphers, the output size will always be less than or
//equal to the input size plus the size of one block.
//That's why we need to add the size of one block here
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc( bufferSize );
char ivVector[kCCBlockSizeAES128+1];
// fetch key data
[key getCString:ivVector maxLength:sizeof( ivVector ) encoding:NSUTF8StringEncoding];
bzero( ivVector, sizeof( ivVector ) ); // fill with zeroes (for padding)
const void *iv=NULL;
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt( kCCEncrypt, kCCAlgorithmAES128, padding,
keyPtr, keySize,
ivKey /* initialization vector (optional) */,
[self bytes], dataLength, /* input */
buffer, bufferSize, /* output */
&numBytesEncrypted );
if( cryptStatus == kCCSuccess )
{
//the returned NSData takes ownership of the buffer and will free it on deallocation
return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
}
free( buffer ); //free the buffer
return nil;
}
- (NSData *)AES256DecryptWithKey:(NSString *)key Data:(NSData*)EncryptedData{
bool same =[self isEqualToData:EncryptedData];
// 'key' should be 32 bytes for AES256, will be null-padded otherwise
char keyPtr[keySize+1]; // room for terminator (unused)
bzero( keyPtr, sizeof( keyPtr ) ); // fill with zeroes (for padding)
// fetch key data
[key getCString:keyPtr maxLength:sizeof( keyPtr ) encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [EncryptedData length];
//See the doc: For block ciphers, the output size will always be less than or
//equal to the input size plus the size of one block.
//That's why we need to add the size of one block here
size_t bufferSize = dataLength +kCCBlockSizeAES128;
void *buffer = malloc( bufferSize );
const void *iv=NULL;
char ivVector[kCCBlockSizeAES128+1];
// fetch key data
[key getCString:ivVector maxLength:sizeof( ivVector ) encoding:NSUTF8StringEncoding];
bzero( ivVector, sizeof( ivVector ) ); // fill with zeroes (for padding)
size_t numBytesDecrypted = 0;
NSData *output_decrypt = [[NSData alloc] init];
CCCryptorStatus cryptStatus = CCCrypt( kCCDecrypt, kCCAlgorithmAES128, padding,
keyPtr, keySize,
ivKey /* initialization vector (optional) */,
[EncryptedData bytes], dataLength, /* input */
buffer,bufferSize ,//bufferSize, /* output */
&numBytesDecrypted );
output_decrypt = [NSMutableData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
same =[self isEqualToData:output_decrypt];
if( cryptStatus == kCCSuccess )
{
//the returned NSData takes ownership of the buffer and will free it on deallocation
NSData *pData = [[NSData alloc]initWithBytes:buffer length:numBytesDecrypted];
return pData;
}
free( buffer ); //free the buffer
return nil;
}
Thanks for looking at this, this was the problem,
output_decrypt = [NSMutableData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
same =[self isEqualToData:output_decrypt];
if( cryptStatus == kCCSuccess )
{
//the returned NSData takes ownership of the buffer and will free it on deallocation
**NSData *pData = [[NSData alloc]initWithBytes:buffer length:numBytesDecrypted];**
return pData;
}
and solutions was;
output_decrypt = [NSMutableData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
same =[self isEqualToData:output_decrypt];
if( cryptStatus == kCCSuccess )
{
//the returned NSData takes ownership of the buffer and will free it on deallocation
return output_decrypt;
}
Not sure, why it was causing problem, of-course i need to change return type and do some handling in the calling function to release the memory.

How to use hex decimal key with AES encryption?

My question is I need to use the following hexadecimal key to encrypt but it assumes it as a string?
key = 0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11
I had tried using [key bytes] instead of keyptr in the CCrypt function but it does't work...
- (NSData *)AES128EncryptWithKey:(NSString *)key theData:(NSData *)Data {
// 'key' should be 32 bytes for AES256, will be null-padded otherwise
char keyPtr[kCCKeySizeAES128]={'1'};; // room for terminator (unused) // oorspronkelijk 256
bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding)
// fetch key data
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
NSLog(#"keyPtr %s",keyPtr);
NSUInteger dataLength = [Data length];
//See the doc: For block ciphers, the output size will always be less than or
//equal to the input size plus the size of one block.
//That's why we need to add the size of one block here
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionECBMode,
keyPtr,
kCCKeySizeAES128, // oorspronkelijk 256
nil, /* initialization vector (optional) */
[Data bytes],
dataLength, /* input */
buffer,
bufferSize, /* output */
&numBytesEncrypted);
if (cryptStatus == kCCSuccess) {
NSLog(#"Encrypt SUCCESS");
//the returned NSData takes ownership of the buffer and will free it on deallocation
return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
}
free(buffer); //free the buffer;
return nil;
}
- (NSData *)AES128DecryptWithKey:(NSString *)key theData:(NSData *)Data{
// 'key' should be 32 bytes for AES256, will be null-padded otherwise
char keyPtr[kCCKeySizeAES128+1]; // room for terminator (unused) // oorspronkelijk 256
bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding)
// fetch key data
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSASCIIStringEncoding];
NSUInteger dataLength = [Data length];
//See the doc: For block ciphers, the output size will always be less than or
//equal to the input size plus the size of one block.
//That's why we need to add the size of one block here
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
size_t numBytesDecrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, kCCOptionECBMode+kCCOptionPKCS7Padding,
keyPtr, kCCKeySizeAES128, // oorspronkelijk 256
NULL /* initialization vector (optional) */,
[Data bytes], dataLength, /* input */
buffer, bufferSize, /* output */
&numBytesDecrypted);
if (cryptStatus == kCCSuccess) {
NSLog(#"Decrypt SUCCESS");
//the returned NSData takes ownership of the buffer and will free it on deallocation
return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
}
free(buffer); //free the buffer;
return nil;
}
You can use NSScanner, like this:
NSString *keyStr = #"0x11,0x12,0x13,0x14,0x13,0x1a,0x1b,0x1c,0x1f,0x11,0x11,0x11,0x11,0x11,0x11,0xfe";
NSScanner *scan = [NSScanner scannerWithString:keyStr];
[scan setCharactersToBeSkipped:[NSCharacterSet characterSetWithCharactersInString:#","]];
unsigned int tmp;
char key[16];
for (int i = 0 ; i != 16 ; i++) {
[scan scanHexInt:&tmp];
key[i] = (char)tmp;
}
At this point, the array key contains 16 bytes of your key converted from hex to bytes.