SecureRandom在Java中安全种子 [英] SecureRandom safe seed in Java

查看:655
本文介绍了SecureRandom在Java中安全种子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这段代码是否安全?

  SecureRandom randomizer =新的SecureRandom(String.valueOf(new Date()。getTime ())的getBytes())。 

这是否是安全随机实例的正确方法?

解决方案

不,您应该避免 SecureRandom(byte [])构造函数。它是不安全的和不可移植的。



它是不可移植的,因为它在Windows和其他操作系统上的行为不同。


$在大多数操作系统中,默认算法为NativePRNG,它从操作系统(通常为/ dev / random)获取随机数据,并忽略您所提供的种子。



在Windows上,默认算法为SHA1PRNG,它将您的种子与计数器相结合,并计算结果的哈希值。



这是您的示例中的坏消息,因为输入(当前UTC时间(以毫秒为单位))具有相对较小的可能值范围。例如,如果攻击者知道RNG在最近48小时内播种,则可以将种子缩小到小于2 28 可能的值,即您只有27位熵。



如果另一方面您在Windows上使用了默认的 SecureRandom()构造函数,那么它将调用本机 CryptoGenRandom 函数来获取128位种子。因此,通过指定您自己的种子,您已经削弱了安全性。



如果您真的要覆盖默认种子(例如单元测试),您还应该指定算法。例如:

  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 /


Is this piece of code safe?

 SecureRandom randomizer = new SecureRandom(String.valueOf(new Date().getTime()).getBytes());

Is this the right way to instance the seed of secure random?

解决方案

No, you should avoid the SecureRandom(byte[]) constructor. It is both unsafe and non-portable.

It is non-portable because it behaves differently on Windows vs. other operating systems.

On most OSes, the default algorithm is "NativePRNG", which obtains random data from the OS (usually "/dev/random") and ignores the seed you provide.

On Windows, the default algorithm is "SHA1PRNG", which combines your seed with a counter and computes a hash of the result.

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.

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"));

See also How to solve performance problem with Java SecureRandom?
and this blog post: http://www.cigital.com/justice-league-blog/2009/08/14/proper-use-of-javas-securerandom/

这篇关于SecureRandom在Java中安全种子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆