0

I have the following code inside the NSData+AES256 class. I am trying AES CBC encryption to a NSString with the following code. I have a key and a iv. But getting null in result. Can not find out what's wrong. This is what I tried-

NSString *initV= @"somekey*********";
NSData *input= [initV dataUsingEncoding:NSUTF8StringEncoding];


size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCModeCBC,
                                      keyPtr, kCCKeySizeAES256,
                                      [input bytes] /* initialization vector (optional) */,
                                      [self bytes], dataLength, /* input */
                                      buffer, bufferSize, /* output */
                                      &numBytesEncrypted);
Mahbub Morshed
  • 915
  • 9
  • 20
  • I'm not a pro iPhone dev or anything. But I noticed that sometimes the IV, and input data will use base64 encryption, or binary encryption. Is your IV/key pair base64, or binary encoded? – Raiden Jul 29 '12 at 05:41
  • Hi thanks for your comment. I was able to solve it by using these following two functions- CCCryptorCreate CCCryptorUpdate Thanks to the last comment [in here](http://stackoverflow.com/questions/4540725/iphone-aes-256-encryption-without-padding) – Mahbub Morshed Jul 29 '12 at 09:11

1 Answers1

0

This is the code that worked for me finally-

-(NSData *)AES256EncryptWithKey:(NSString *)key {
NSUInteger dataLength = [self length];
NSData *keyGiven= [key dataUsingEncoding:NSUTF8StringEncoding];    

size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);

NSString *initV= @"***************";
NSData *input= [initV dataUsingEncoding:NSUTF8StringEncoding];

size_t numBytesEncrypted = 0;

CCCryptorRef ccRef;
CCCryptorCreate(kCCEncrypt, kCCAlgorithmAES128, 0, (const void *)[keyGiven bytes], kCCKeySizeAES256, (const void *)[input bytes], &ccRef);
CCCryptorStatus cryptStatus = CCCryptorUpdate(ccRef, [self bytes], dataLength, buffer, bufferSize, &numBytesEncrypted);
CCCryptorRelease(ccRef);

if (cryptStatus == kCCSuccess) {
    return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
}
free(buffer); //free the buffer;
return nil;
}

I am converting an NSString to NSData and passing it for encryption. The NSString must be of 16 characters. If it is of less than 16 characters I make it 16 by appending spaces.

I don't know if this is going to help anybody. But I just thought I should share. Thanks.

Mahbub Morshed
  • 915
  • 9
  • 20
  • Note that this is an extremely insecure way to create a key. You're throwing away almost all of your entropy. See http://robnapier.net/blog/aes-commoncrypto-564 for a full discussion and how to do this correctly. You're also using a fixed IV, which is extremely insecure as well. – Rob Napier Aug 13 '12 at 18:07