Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SecureRandom self-seeding

Tags:

java

random

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 the setSeed method. If setSeed is not called, the first call to nextBytes will force the SecureRandom object to seed itself. This self-seeding will not occur if setSeed 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 class Random 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.

like image 538
effeffe Avatar asked Jun 09 '13 11:06

effeffe


1 Answers

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.

like image 106
Alex D Avatar answered Sep 20 '22 16:09

Alex D