I got this code from http://www.ravenblast.com/index.php/blog/android-password-text-encryption/ and, although it works, I have a growing suspicion it's not secure enough. There isn't any initialization vector which seems to be necessary according other sources.
public static String encrypt(String toEncrypt, byte[ ] key) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[ ] encryptedBytes = cipher.doFinal(toEncrypt.getBytes());
String encrypted = Base64.encodeBytes(encryptedBytes);
return encrypted;
}
public static String decrypt(String encryptedText, byte[ ] key) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] toDecrypt = Base64.decode(encryptedText);
byte[] encrypted = cipher.doFinal(toDecrypt);
return new String(encrypted);
}
getBytes()
is a bad idea as well, since it uses a platform/culture dependent encoding. Use UTF-8 instead. – Adam