11

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.

8
  • 2
    next(32) calls nextBytes.
    – assylias
    Commented Jun 9, 2013 at 11:14
  • @assylias: What makes you think that? I don't see such a call in the source code of JDK 1.7?
    – meriton
    Commented Jun 9, 2013 at 11:20
  • 1
    @assylias: looking at this source code (line 472) it seems true, however it is not mentioned in the documentation.
    – effeffe
    Commented Jun 9, 2013 at 11:27
  • Ah, nevermind. Yes, SecureRandom overrides next(int) to use nextBytes.
    – meriton
    Commented Jun 9, 2013 at 11:30
  • @assylias, you could post an answer to this question.
    – Alex D
    Commented Jun 9, 2013 at 11:36

1 Answer 1

6

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.

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.