Question

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);
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top