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

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).


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.