問題描述
我正在為 android 中的 PBE 實現和 AES 加密引擎,我找到了兩種方法來實現 IV 的創建,我想知道哪種方法更好更安全地獲取 IvParameterSpec代碼>:
I'm implementing and AES encryption engine for PBE in android, and I've found two ways to implement the creation of the IV and I would like to know which one is better and more secure for getting IvParameterSpec
:
方法#1:
SecureRandom randomSecureRandom = SecureRandom.getInstance("SHA1PRNG");
byte[] iv = new byte[cipher.getBlockSize()];
randomSecureRandom.nextBytes(iv);
IvParameterSpec ivParams = new IvParameterSpec(iv);
方法#2:
AlgorithmParameters params = cipher.getParameters();
byte[] iv2 = params.getParameterSpec(IvParameterSpec.class).getIV();
ivParams = new IvParameterSpec(iv2);
推薦答案
我會使用方法#1,因為 Java API 為 Cipher.init()
只接受加密/解密模式和密鑰的API:
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).
(強調我的).
所以不清楚選擇方法2時不同的提供者會做什么.查看 Android 源代碼,似乎至少某些版本(包括版本 21?)將不會創建隨機 IV - 隨機 IV 創建似乎已被注釋掉.
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.
方法 1 也更透明,而且 - 在我看來 - 對眼睛更容易.
Method 1 is also more transparent and it is - in my opinion - easier on the eyes.
請注意,通常最好使用 new SecureRandom()
并讓系統找出最好的 RNG.SHA1PRNG"
定義不明確,可能因實現而異,并且已知存在實現弱點,尤其是在 Android 上.
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);
<小時>
請注意,GCM 模式最適合 12 字節 IV 而不是 16 字節 IV - AES 的塊大小.
Beware that GCM mode works best with a 12 byte IV instead of the 16 byte IV - the block size of AES.
這篇關于在 Java 中為 AES 生成隨機 IV的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!