I am trying to encrypt a string using AES 128 bit encryption, but the encrypted data converted, when converted to a string, always returns null.
NSString *iv = @"fedcba9876543210";
NSString *key = @"0123456789abcdef";
- (NSData *)AES128EncryptWithKey
{
char keyPtr[kCCKeySizeAES128 + 1];
bzero( keyPtr, sizeof( keyPtr ) );
[key getCString:keyPtr maxLength:sizeof( keyPtr ) encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [self length];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc( bufferSize );
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt( kCCEncrypt, kCCAlgorithmAES128, kCCOptionECBMode | kCCOptionPKCS7Padding,
keyPtr, kCCKeySizeAES128,
NULL ,
[self bytes], dataLength,
buffer, bufferSize,
&numBytesEncrypted );
if( cryptStatus == kCCSuccess )
{
return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
}
}
This is my encryption function.
NSData *data = [@"String to encrypt" dataUsingEncoding:NSUTF8StringEncoding];
NSData *encryptedData = [[NSData alloc] init];
encryptedData = [data AES128EncryptWithKey];
NSLog(@"Encrypted Data Length %d", [encryptedData length]);
if (encryptedData != nil)
{
NSString* myString;
myString = [[NSString alloc] initWithData:encryptedData encoding:NSUTF8StringEncoding];
NSString* newStr = [NSString stringWithUTF8String:[encryptedData bytes]];
}
After encryption, encryption data length is reported as 16 but after converting it to an NSString
it returns null. If I use stringWithUTF16String
to convert it, it returns like "軽ﶁែ뼐끨驂퐇". What is the issue here?
Finally I got it.. As Joachim suggested I used the following method and it worked..
unichar* hexChars = (unichar*)malloc(sizeof(unichar) * (data.length*2));
unsigned char* bytes = (unsigned char*)data.bytes;
for (NSUInteger i = 0; i < data.length; i++) {
unichar c = bytes[i] / 16;
if (c < 10) c += '0';
else c += 'a' - 10;
hexChars[i*2] = c;
c = bytes[i] % 16;
if (c < 10) c += '0';
else c += 'a' - 10;
hexChars[i*2+1] = c;
}
NSString* retVal = [[NSString alloc] initWithCharactersNoCopy:hexChars
length:data.length*2
freeWhenDone:YES];