Random IV Generation for AES in Java

I use the AES encryption mechanism for PBE in android, and I found two ways to implement IV creation, and I would like to know which one is better and safer to get IvParameterSpec :

Method # 1:

 SecureRandom randomSecureRandom = SecureRandom.getInstance("SHA1PRNG"); byte[] iv = new byte[cipher.getBlockSize()]; randomSecureRandom.nextBytes(iv); IvParameterSpec ivParams = new IvParameterSpec(iv); 

Method No. 2:

 AlgorithmParameters params = cipher.getParameters(); byte[] iv2 = params.getParameterSpec(IvParameterSpec.class).getIV(); ivParams = new IvParameterSpec(iv2); 
+9
java cryptography aes
source share
1 answer

I would use method # 1 , because the Java API defines the following for the Cipher.init() API, which simply uses the encryption / decryption mode and key:

If this instance of the cipher needs any algorithm parameters or random values ​​that the specified key cannot provide, it is assumed that the base implementation of this cipher will generate the required parameters (using its provider or random values).

(my emphasis).

So it’s not clear what the different providers will do when choosing method 2 . Looking at the Android source code, it seems that at least some versions (including version 21?) Will not create a random IV - the random creation of an IV seems to be commented out.

Method 1 is also more transparent and, in my opinion, easier for the eyes.


Note that it is usually best to use new SecureRandom() and let the system figure out which RNG is the best. "SHA1PRNG" not clearly defined, may differ in different implementations and, as you know, has implementation flaws, especially in Android.


Thus, the end result should be something like this:

 SecureRandom randomSecureRandom = new SecureRandom(); byte[] iv = new byte[cipher.getBlockSize()]; randomSecureRandom.nextBytes(iv); IvParameterSpec ivParams = new IvParameterSpec(iv); 

Remember that GCM works best with a 12-byte IV instead of a 16-byte IV β€” the AES block size.

+15
source share

All Articles