我找到了很多关于 SecureRandom
的例子看起来像这样的类:
Random random = new SecureRandom();
int randomInteger = random.nextInt();
或者像这样:
try
{
Random random = SecureRandom.getInstance("SHA1PRNG");
int randomInteger = random.nextInt();
}
catch (NoSuchAlgorithmException exception)
{
// ...
}
或类似的东西。
然而,SecureRandom()
和 SecureRandom.getInstance(String)
在他们的文档中有这部分:
The returned
SecureRandom
object has not been seeded. To seed the returned object, call thesetSeed
method. IfsetSeed
is not called, the first call tonextBytes
will force theSecureRandom
object to seed itself. This self-seeding will not occur ifsetSeed
was previously called.
因此,Random
在上面的示例中,对象从未在创建时播种。 nextInt()
的文档(来自 Random
类文档,它没有在 SecureRandom
中被覆盖)状态:
The method
nextInt
is implemented by classRandom
as if by:
public int nextInt() {
return next(32);
}
因此,没有调用 nextBytes
方法,next
的文档都不是SecureRandom
中的方法说明了有关播种的任何内容。
我的问题是:上面的 Random
对象确定是播种的吗?所有这些例子都是错误的还是我遗漏了什么?我可以安全地使用这样的非种子随机数生成器吗?
正如评论中正确指出的那样,查看 source code似乎 next
调用了 nextBytes
,因此初始化了种子,但是文档中没有提到这一点。
最佳答案
对于 Sun 的 JRE,是否可以在没有种子的情况下使用 SecureRandom
?不,因为@assylias 在他的评论中指出的原因。 nextInt
调用 nextBytes
,确保 SecureRandom
已播种。
Java 平台的替代实现是否可以提供一个 SecureRandom
,它可以在没有种子的情况下使用,同时仍然符合文档化的接口(interface)?是的。那会很糟糕吗?哦是的。会有实现者愚蠢到做这样的事情吗?可能不会。这是 Java 程序员需要担心的事情吗?没有。
关于java - SecureRandom 自播种,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17008967/