3

I'm using the AES algorithm to encrypt data on my iPhone and Android apps before sending it to a .NET server.

iPhone encryption works fine (the .NET server code decrypts it no problem).

Android encryption works fine for clear text strings of < 16 chars. For clear text strings >= 16 chars, the first encrypted "chunk" is the same as the iPhone, the second encrypted chunk is completely different. My key length is 16 chars.

Here is the Android code (which works fine up to 16 chars):

byte[] valueData = value.getBytes();   
byte[] keyData = skey.getBytes();

SecretKeySpec skeySpec = new SecretKeySpec(keyData, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7PADDING");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);

byte[] valueEncryptedData = cipher.doFinal(valueData);
String valueEncryptedString = Base64.encodeToString(valueEncryptedData, Base64.DEFAULT);

return valueEncryptedString;

And here is my iOS code, which works fine:

StringEncryption *crypto = [[StringEncryption alloc] init];
CCOptions padding = kCCOptionPKCS7Padding;

NSData *valueData = [value dataUsingEncoding:NSUTF8StringEncoding];
NSData *keyData = [skey dataUsingEncoding:NSUTF8StringEncoding];
NSData *valueEncryptedData = [crypto encrypt:valueData key:keyData padding:&padding];
NSString *valueEncryptedString = [valueEncryptedData base64EncodingWithLineLength:0];

I suspect the problem is something trivial. E.g. perhaps I'm using the wrong Cipher initialization and I should be using CBC instead of ECB. However, the output using Cipher.getInstance("AES/CBC/PKCS7PADDING") doesn't produce the desired result either, (in fact, worse as the encrypted value is completely different to the iPhone encrypted value, not just diverging after the first 16 chars).

tomblah
  • 791
  • 3
  • 9
  • 21
  • Are you using a simple call to `CCCrypt` in the encrypt function? You should show how you're performing the encryption in iOS - the crypto calls would be preferable – Anya Shenanigans Feb 27 '13 at 09:29
  • Please show your decryption code as well. – Nickolay Olshevsky Feb 27 '13 at 09:36
  • Hi @Patesh, we're using the iOS encryption code written by David Veksler http://automagical.rationalmind.net/2009/02/12/aes-interoperability-between-net-and-iphone/ (see StringEncryption.m in the zip file) and http://stackoverflow.com/questions/538435/aes-interoperability-between-net-and-iphone/ – tomblah Feb 27 '13 at 09:41

1 Answers1

2

Most likely you are using incorrect cipher mode. And, most likely, you should use CBC instead of ECB. And, it doesn't work from the first try since CBC needs IV (initial vector), and different encryption schemes can use different default vectors.

Nickolay Olshevsky
  • 13,706
  • 1
  • 34
  • 48