use*_*396 11 java cryptography aes initialization-vector
我正在为Android中的PBE实现和AES加密引擎,我发现了两种方法来实现IV的创建,我想知道哪一个更好,更安全得到IvParameterSpec:
方法#1:
SecureRandom randomSecureRandom = SecureRandom.getInstance("SHA1PRNG");
byte[] iv = new byte[cipher.getBlockSize()];
randomSecureRandom.nextBytes(iv);
IvParameterSpec ivParams = new IvParameterSpec(iv);
Run Code Online (Sandbox Code Playgroud)
方法#2:
AlgorithmParameters params = cipher.getParameters();
byte[] iv2 = params.getParameterSpec(IvParameterSpec.class).getIV();
ivParams = new IvParameterSpec(iv2);
Run Code Online (Sandbox Code Playgroud)
Maa*_*wes 18
我使用方法#1,因为Java API为Cipher.init()刚刚采用加密/解密模式和密钥的API指定了以下内容:
如果此密码实例需要指定密钥无法提供的任何算法参数或随机值,则应使用此密码的基础实现生成所需参数(使用其提供程序 或 随机值).
(强调我的).
因此,当选择方法2时,不清楚不同的提供者将做什么.看看Android源代码,似乎至少有些版本(包括版本21?)不会创建随机IV - 随机IV创建似乎被注释掉了.
方法1也更透明,在我看来 - 眼睛更容易.
请注意,通常最好使用new SecureRandom()并让系统确定哪个RNG最佳."SHA1PRNG"没有明确定义,可能因实现而异,并且已知具有实现弱点,尤其是在Android上.
所以最终结果应该是这样的:
SecureRandom randomSecureRandom = new SecureRandom();
byte[] iv = new byte[cipher.getBlockSize()];
randomSecureRandom.nextBytes(iv);
IvParameterSpec ivParams = new IvParameterSpec(iv);
Run Code Online (Sandbox Code Playgroud)
请注意,GCM模式最适合使用12字节IV而不是16字节IV - AES的块大小.
| 归档时间: |
|
| 查看次数: |
18872 次 |
| 最近记录: |