I'm stuck trying to decrypt some AES encrypted data sent by a server to my app.
In order to distill the problem down I've written a small java program that emulates what the server is doing. It encrypts some test data using AES then encodes it as Base64:
AesCipherService cipherService = new AesCipherService();
cipherService.setKeySize(128);
String stringKey = "2EE1F10212ADD4BE";
byte[] keyAsBytes = stringKey.getBytes();
String text = "text to encrypt";
byte[] encryptedBytes = cipherService.encrypt(text.getBytes(), keyAsBytes).getBytes();
String base64String = Base64.encodeToString(encryptedBytes);
System.out.println(base64String);
// Reverse the process to check can retrieve "text to encrypt":
byte[] bytesToDecode = Base64.decode(base64String);
byte[] decryptedBytes = cipherService.decrypt(bytesToDecode, keyAsBytes).getBytes();
String decryptedString = new String(decryptedBytes);
System.out.println(decryptedString);
When run this is the output:
R5UBpP30YjX9Ae2HoPb2Rrfi5rQJY2d0ac1+zaIX5A4=
text to encrypt
So I can successfully encrypt the data, print it out. Then if I unencrypt it the original text is displayed, so everything here is working fine.
Now here is my Obj-C code where I attempt to decrypt the data encrypted from the Java code. I've copied/pasted the encrypted data from the NetBeans IDE output window as the source data of the obj-c content to decrypt:
- (void) decryptData
{
NSData* dataToDecrypt = [[NSData alloc] initWithBase64EncodedString: @"R5UBpP30YjX9Ae2HoPb2Rrfi5rQJY2d0ac1+zaIX5A4=" options: 0];
NSString* key = @"2EE1F10212ADD4BE";
char keyPtr[kCCKeySizeAES128];
bzero(keyPtr, sizeof(keyPtr));
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [dataToDecrypt length];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
size_t numBytesDecrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,
kCCAlgorithmAES,
kCCOptionPKCS7Padding,
keyPtr,
kCCBlockSizeAES128,
keyPtr,
[dataToDecrypt bytes],
dataLength,
buffer,
bufferSize,
&numBytesDecrypted);
if (cryptStatus == kCCSuccess) {
NSLog(@"Success");
NSData* unencryptedData = [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
Byte *unencryptedAsBytes = (Byte*)malloc(unencryptedData.length);
memcpy(unencryptedAsBytes, [unencryptedData bytes], unencryptedData.length);
NSString *decryptedString = [NSString stringWithUTF8String:[unencryptedData bytes]];
NSLog(@"%@", decryptedString);
}
}
When this is run the status is kCCSuccess and numBytesDecrypted is 32 (the same as dataLength) but the decrypted string is not "text to encrypt", decryptedString is nil and if I po unencryptedAsBytes in Xcode's console it displays this:
"\aY|\376\347cD*\320NC\x14\x91C\x88\301\341z\xaca\x11\371
Any idea what is the problem here?
AesCipherServicedocumented? Are you using the key as the IV, that is not secure. 5. Perhaps theIV is the first 16-bytes in the encrypted data, that is not uncommon.