Android AES and init vector

I have a problem with AES encryption and decryption: I can completely change my IV, and yet I can decode my data.

public static final byte[] IV = { 65, 1, 2, 23, 4, 5, 6, 7, 32, 21, 10, 11, 12, 13, 84, 45 }; public static final byte[] IV2 = { 65, 1, 2, 23, 45, 54, 61, 81, 32, 21, 10, 121, 12, 13, 84, 45 }; public static final byte[] KEY = { 0, 42, 2, 54, 4, 45, 6, 7, 65, 9, 54, 11, 12, 13, 60, 15 }; public static final byte[] KEY2 = { 0, 42, 2, 54, 43, 45, 16, 17, 65, 9, 54, 11, 12, 13, 60, 15 }; //public static final int BITS = 256; public static void test() { try { // encryption Cipher c = Cipher.getInstance("AES"); SecretKeySpec keySpec = new SecretKeySpec(KEY, "AES"); c.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(IV)); String s = "Secret message"; byte[] data = s.getBytes(); byte[] encrypted = c.doFinal(data); String encryptedStr = ""; for (int i = 0; i < encrypted.length; i++) encryptedStr += (char) encrypted[i]; //decryoption Cipher d_c = Cipher.getInstance("AES"); SecretKeySpec d_keySpec = new SecretKeySpec(KEY, "AES"); d_c.init(Cipher.DECRYPT_MODE, d_keySpec, new IvParameterSpec(IV2)); byte[] decrypted = d_c.doFinal(encrypted); String decryptedStr = ""; for (int i = 0; i < decrypted.length; i++) decryptedStr += (char) decrypted[i]; Log.d("", decryptedStr); } catch (Exception ex) { Log.d("", ex.getMessage()); } } 

Any ideas what I'm doing wrong? How can I get 256-bit AES encryption (only change the key to a 32-byte long array?)

Encryption is a new topic for me, so please for friendly answers for beginners.

+4
source share
1 answer

You do not specify the encryption mode, so the provider probably defaults to the electronic codebook ("ECB") mode and completely ignores IV. You can verify this by comparing the ciphertext generated by several runs of your program; I assume that they are all identical.

The encryption chain ("CBC") is usually supported and widely used, but the correct mode depends on your application.

You do not specify an add-on, so the provider chooses the default value. What JCE calls "PKCS5Padding" is a common choice for symmetric ciphers.

Instead of specifying "AES" as the algorithm, specify the full specification, including the algorithm, mode, and addition, for example, "AES / CBC / PKCS5Padding".

You do not need to specify the size of the AES key in the Cipher name; this is inferred from the size of the key that you use to initialize the encryption.

+8
source

Source: https://habr.com/ru/post/1344292/


All Articles