Question

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);
}
Was it helpful?

Solution

Yes, it's not very secure. There is no IV because there is no block chaining.

The AES algorithm can only encrypt blocks of 128 bytes, no matter the size of the key (it is unrelated). How those blocks are chained together is another problem. The simplest approach is to encrypt each block separately from the others (ECB mode), like they were separate messages. The Wikipedia article I linked tells you when and why this is not secure, and other methods (namely, CBC mode) are preferred.

When you do Cipher cipher = Cipher.getInstance("AES"); you are given an AES cipher in ECB mode. There is no immediate danger, but if your messages have recurring patterns this can lead to situations like the following:

Original: enter image description here Encrypted: encrypted

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top