Generating random IV for AES in Java

做~自己de王妃 提交于 2019-11-28 19:52:12

I'd use method #1, because the Java API specifies the following for the Cipher.init() API that just takes the encryption/decryption mode and key:

If this cipher instance needs any algorithm parameters or random values that the specified key can not provide, the underlying implementation of this cipher is supposed to generate the required parameters (using its provider or random values).

(emphasis mine).

So it is not clear what different providers will do when method 2 is chosen. Looking at the Android source code, it seems that at least some versions (including version 21?) will not create a random IV - the random IV creation seems commented out.

Method 1 is also more transparent and it is - in my opinion - easier on the eyes.


Note that it is generally better to use new SecureRandom() and let the system figure out which RNG is best. "SHA1PRNG" is not well defined, may differ across implementations and is known to have had implementation weaknesses, especially on Android.


So the end result should be something like:

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

Beware that GCM mode works best with a 12 byte IV instead of the 16 byte IV - the block size of AES.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!