user2246481
user2246481

Reputation: 31

Does calling Java SecureRandom.getInstance and nextBytes multiple times block on /dev/random?

I have a method which is called N number of times for file encryption. In the method, this is how I create the salt:

public void method(...){
      ...
      byte[] salt = new byte[8];
      SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG", 
          "SUN");
      secureRandom.nextBytes(salt);
      ...
}

I read that the SecureRandom object is seeded when you call nextBytes and will only block on /dev/random the very first time you call nextBytes since the class's variable seedGenerator is static (https://www.cigital.com/blog/securerandom-implementation/).

JavaDocs on SecureRandom.getInstance(String algorithm, String provider) says: 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.

My question is, will my code block on /dev/random if I keep creating SecureRandom instances and calling nextBytes?

Thanks in advance!

Upvotes: 2

Views: 444

Answers (1)

user268396
user268396

Reputation: 11986

The first call to /dev/random may block until sufficient entropy is available, which means the first call to your nextBytes() may block if you don't seed manually. Subsequent calls should never block because, whatever the implementation of SecureRandom may be, once entropy has been obtained it will not disappear and so subsequent reads from /dev/random will not block (i.e. once the first read of /dev/random succeeds no subsequent read of /dev/random should fail for lack of entropy).

Upvotes: 1

Related Questions