Diky Iskandar Diky Iskandar - 24 days ago 12
Java Question

eclipse : key on Android AES encryption and decryption

I just want to ask.

I have SMS application with AES encryption for android on eclipse, but I had a problem.
The problem is when I put the key in less than 16 characters, the message can not be encrypted. but if the key is 16 characters, the message can be encrypted.

I want to insert the key, regardless of the amount. The key can be generated to 16 characters, to get 128 bit. So, how the code is supposed to solve that problem?

Thanks before.. I hope you can help me.

public class AES {
public static String encrypt(String message, String key){
try {
SecretKeySpec KS = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, KS);
byte[] encrypted = cipher.doFinal(message.getBytes());
return Base64.encodeToString(encrypted, Base64.NO_PADDING);
} catch (Exception e) {
return "ERROR:"+e.getMessage();
}
}

public static String decrypt(String chiperText, String key){
try {

SecretKeySpec KS = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, KS);
byte[] decrypted = cipher.doFinal(Base64.decode(chiperText, Base64.NO_PADDING));
return new String(decrypted);
} catch (Exception e) {
return "ERROR";
}
}

Answer

Your code is insecure because you use a password as key directly via password.getBytes().

NEVER EVER DO THIS!

Use a proper key derivation function like PBKDF2 which generates the key based on the password. The same password together with the same PBKDF2 parameters will end up in the same key.

For more details please read for example this blog post: Using Password-based Encryption on Android.