Seeding a SecureRandom
by calling java.security.SecureRandom#setSeed
is not necessary, and actually, shouldn't be done unless you have a really good source of entropy and java.lang.System#currentTimeMillis
definitely is not one.
Now, from your example where it was producing two different outputs even when the seed was the same. It is a behaviour that I observed in the DRBG
SecureRandom
implementation in Java 10, where both random numbers produced will differ during one execution but will remain constant if the program restarts:
public class SessionIdTest {
public static void main (String args[]) throws NoSuchAlgorithmException {
// Hardcoded seed to evidence the deterministic behavior when the program restarts.
long seed = 1000;
{
SecureRandom random = SecureRandom.getInstance("DRBG");
random.setSeed(seed);
BigInteger a = new BigInteger(130, random);
System.out.println(a);
}
{
SecureRandom random = SecureRandom.getInstance("DRBG");
random.setSeed(seed);
BigInteger a = new BigInteger(130, random);
System.out.println(a);
}
}
}
So the previous will always generate something like this:
724996208419722369188940556616693042555
796664555436785984208644362540465534270
And the differing values in one execution have its cause in a global state being updated every time a DRBG
implementation is created.
Now, if you try the SHA1PRNG
implementation, both random numbers will be the same and they will remain constant through program restarts:
public class SessionIdTest {
public static void main (String args[]) throws NoSuchAlgorithmException {
// Hardcoded seed to evidence the deterministic behavior when the program restarts.
long seed = 1000;
{
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
random.setSeed(seed);
BigInteger a = new BigInteger(130, random);
System.out.println(a);
}
{
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
random.setSeed(seed);
BigInteger a = new BigInteger(130, random);
System.out.println(a);
}
}
}
So the previous will always generate something like this:
251586625089438840547467272692377284989
251586625089438840547467272692377284989
Finally, in both cases you can confirm that there is a deterministic behavior based on the provided seed, so, do not seed these SecureRandom
s manually unless you have a very good source of entropy and again, the current time is not one!. Just let them seed themselves which is safer.