I try to decrypt data that was originally encrypted with Objective-C in Java.
There are other questions mentioning this but they are really cluttered and many of them aren't solved yet therefore I will post my own.
This is the code that encrypts the data:
- (int) encryptWithKey: (NSString *) key
{
// 'key' should be 32 bytes for AES256, will be null-padded otherwise
char * keyPtr[kCCKeySizeAES128+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];
// encrypts in-place, since this is a mutable data object
size_t numBytesEncrypted = 0;
CCCryptorStatus result = CCCrypt( kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
keyPtr, kCCKeySizeAES128,
NULL /* initialization vector (optional) */,
[self mutableBytes], [self length], /* input */
[self mutableBytes], [self length]+32, /* output */
&numBytesEncrypted );
return numBytesEncrypted;
}
I execute this function and write the resulting data to the disc with this code:
NSString* strTest = @"Hallo Welt!";
NSLog(@"strTest = %@", strTest);
NSMutableData *protectedData = [NSMutableData dataWithData:[strTest dataUsingEncoding:NSUTF8StringEncoding]];
int laenge = [protectedData encryptWithKey:@"keykeykeykeykeykeykeykey"];
NSData* dataOutput = [[NSData alloc] initWithBytes:[protectedData bytes] length:laenge];
[dataOutput writeToFile:@"/encryptedFileObjC" atomically:YES];
In Java I use this code to try to achieve the same behavior:
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
String keyString = "keykeykeykeykeykeykeykey";
byte[] keyBytes = keyString.getBytes("UTF-8");
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(keyBytes, "AES"),
new IvParameterSpec(new byte[16]));
byte[] resultBytes = cipher.doFinal("Hallo Welt!".getBytes("UTF8"));
FileOutputStream out =
new FileOutputStream(new File("encryptedFileJava"));
out.write(resultBytes);
out.close();
If I now try decrypting the file that was encrypted via Objective-C I get a bad padding Exception. If I open the two files with the encrypted content they are different:
Hallo Welt! encrypted with Java: 96 C5 CB 51 39 B5 27 FB B3 93 BF 92 18 BB 16 9B
Hallo Welt! encrypted with ObjC: A3 61 32 8E A5 E6 66 E0 41 64 89 25 62 D3 21 16
Shouldn't the file content be the same? I think I don't got all the parameters for the algorithm the same in the two languages.
I need to alter the Java Code to get the same result as the Objective-C Code to be able to decrypt some data that was encrypted with Objective-C.