I found a lot of examples about the SecureRandom
class that look like this:
Random random = new SecureRandom();
int randomInteger = random.nextInt();
or like this:
try
{
Random random = SecureRandom.getInstance("SHA1PRNG");
int randomInteger = random.nextInt();
}
catch (NoSuchAlgorithmException exception)
{
// ...
}
or something similar.
However, both SecureRandom()
and SecureRandom.getInstance(String)
have this part in their documentation:
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.
So, the Random
object is never seeded at creation time in the above examples. The documentation of nextInt()
(from the Random
class documentation, it's not overridden in SecureRandom
) states:
The method
nextInt
is implemented by classRandom
as if by:
public int nextInt() {
return next(32);
}
So, there is no call to a nextBytes
method, neither the documentation for the next
method in SecureRandom
says anything about seeding.
My questions are: are the above Random
objects seeded for sure? Are all those examples wrong or am I missing something? Can I safely use such an unseeded random numbers generator?
As correctly pointed out in a comment, looking at the source code it seems like next
calls nextBytes
, therefore initializing the seed, however this is not mentioned in the documentation.
With Sun's JRE, can a SecureRandom
be used without seeding? No, for the reason @assylias pointed out in his comment. nextInt
calls nextBytes
, which ensures the SecureRandom
is seeded.
Could an alternate implementation of the Java platform provide a SecureRandom
which could be used without seeding, while still conforming to the documented interface? Yes. Would that be bad? Oh yes. Would any implementer be so stupid as to do such a thing? Probably not. Is it something Java programmers need to worry about? No.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With