SecureRandom safe seed in Java(Java中的SecureRandom安全种子)
问题描述
这段代码安全吗?
SecureRandom randomizer = new SecureRandom(String.valueOf(new Date().getTime()).getBytes());
这是实例化安全随机种子的正确方法吗?
Is this the right way to instance the seed of secure random?
推荐答案
不,你应该避免使用 SecureRandom(byte[])
构造函数.它既不安全也不便携.
No, you should avoid the SecureRandom(byte[])
constructor. It is both unsafe and non-portable.
它是不可移植的,因为它在 Windows 和其他操作系统上的行为不同.
It is non-portable because it behaves differently on Windows vs. other operating systems.
在大多数操作系统上,默认算法是NativePRNG",它从操作系统获取随机数据(通常是 "/dev/random"
)并忽略您提供的种子.
On most OSes, the default algorithm is "NativePRNG", which obtains random data from the OS (usually "/dev/random"
) and ignores the seed you provide.
在 Windows 上,默认算法是SHA1PRNG",它将您的种子与计数器结合起来并计算结果的哈希值.
On Windows, the default algorithm is "SHA1PRNG", which combines your seed with a counter and computes a hash of the result.
在您的示例中这是个坏消息,因为输入(当前 UTC 时间,以毫秒为单位)的可能值范围相对较小.例如,如果攻击者知道 RNG 是在过去 48 小时内播种的,他们可以将种子缩小到小于 228 个可能的值,即您只有 27 位的熵.
This is bad news in your example, because the input (the current UTC time in milliseconds) has a relatively small range of possible values. For example if an attacker knows that the RNG was seeded in the last 48 hours, they can narrow the seed down to less than 228 possible values, i.e. you have only 27 bits of entropy.
另一方面,如果您在 Windows 上使用了默认的 SecureRandom()
构造函数,它将调用本机 CryptoGenRandom
函数来获取 128 位种子.因此,通过指定您自己的种子,您已经削弱了安全性.
If on the other hand you had used the default SecureRandom()
constructor on Windows, it would have called the native CryptoGenRandom
function to get a 128-bit seed. So by specifying your own seed you have weakened the security.
如果您真的想覆盖默认种子(例如用于单元测试),您还应该指定算法.例如
If you really want to override the default seed (e.g. for unit testing) you should also specify the algorithm. E.g.
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
sr.setSeed("abcdefghijklmnop".getBytes("us-ascii"));
另请参阅如何使用 Java SecureRandom 解决性能问题?
和这篇博文:http://www.cigital.com/justice-league-blog/2009/08/14/proper-use-of-javas-securerandom/
这篇关于Java中的SecureRandom安全种子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java中的SecureRandom安全种子


基础教程推荐
- Java:带有char数组的println给出乱码 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 降序排序:Java Map 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01