Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between nextXXX() and generateSeed() function in SecureRandom?

What is the difference between functions nextXXX() - such as like nextInt(), nextFloat() and nextBytes() - and generateSeed(int numBytes): byte[] in the SecureRandom class of Java?

In what way does "the seed generation algorithm" in generateSeed differ from the secure random generator itself?

like image 543
Ashok Avatar asked Aug 09 '14 16:08

Ashok


2 Answers

generateSeed() does not use any bytes generated by the random number generator. Instead, it is just a pass through to the entropy source that the SecureRandom implementation uses to seed itself when and if it is seeding itself.


So for instance calling the following code on an Oracle provided Java SE:

// initSeed is just zero valued bytes
byte[] initSeed = new byte[16];

SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(initSeed);

byte[] seed = secureRandom.generateSeed(16);

byte[] data = new byte[16];
secureRandom.nextBytes(data);

System.out.printf("Seed: %s%n", Hex.toHexString(seed));
System.out.printf("Data: %s%n", Hex.toHexString(data));

Will actually give back different values for seed, and always the same value for data. In other words, the generateSeed uses the operating system to ask for 16 bytes of entropy, while the random number generator is only seeded with the initSeed and thus will always generate the same stream of pseudo random numbers.

Warning: this is just to illustrate the point; you should not rely on any SecureRandom instance to return anything but random bytes. The behavior with regards to setSeed differs per implementation. The Oracle "SHA1PRNG" provider uses it as the only seed, others may choose to mix it into the state of the PRNG (for instance later Android implementations will always generate random data).

like image 199
Maarten Bodewes Avatar answered Sep 20 '22 20:09

Maarten Bodewes


Random number functions depend on an initial value from which they generate a sequence of random numbers (read up on PRNG - Pseudo Random Number Generation). The next functions will return the next number generated from that initial value (the seed). generateSeed() will generate a new initial value for a PRNG to use.

like image 39
roelofs Avatar answered Sep 18 '22 20:09

roelofs