Is this AES encryption secure enough?
Asked Answered
P

1

6

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);
}
Protoxylem answered 18/2, 2013 at 12:52 Comment(2)
You need an IV and a MAC. Having a MAC in an encrypt-then-mac scheme, or using specialized authenticated encryption is very important when you face an active attacker. Else it's likely that the attacker can trick you into decrypting a message for him. Padding oracles are a practical attack. If this is ECB(I'm not familiar enough with the API to see that), you need to switch to a better mode as well.Adam
Using getBytes() is a bad idea as well, since it uses a platform/culture dependent encoding. Use UTF-8 instead.Adam
D
10

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

Deductible answered 18/2, 2013 at 12:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.