javarandomsecure-random

Should SecureRandom be used as singleton or a new object should be created each time random number is generated?


I am using SecureRandom to generate random numbers.

Does it make any difference with respect to predictability of next number generated if the SecureRandom object is a singleton or a new object is created every time a random number is generated?

Singleton:

public RequestIdGenerator {
    private static SecureRandom secureRandom = new SecureRandom();

    public static int generateRequestId() {
        secureRandom.nextInt(100_000_000);
    }
}

vs.

New object for each time random number is generated:

public RequestIdGenerator {

    public static int generateRequestId() {
        new SecureRandom().nextInt(100_000_000);
    }
}

This question arose after reading about this answer related to 'Predictability of Linear Congruential Generators'.


Solution

  • Should SecureRandom be used as singleton or a new object should be created each time random number is generated?

    You should not create many SecureRandom instances. It is expensive, and liable to drain your system's source of entropy (randomness).

    If you run out of entropy, the SecureRandom creation is liable to block in a syscall ... waiting ... for ... more entropy to be harvested.

    Does it make any difference with respect to predictability.

    It should not make any difference to predictability. If you treat a seeded SecureRandom as a black box, it should not be possible to predict the next number unless you know the seed and the previous history of the generator.

    The caveat is that a flawed implementation of a secure random number generator may not actually be secure. (But the flipside is that the entropy you are using to generate seeds may not be as random as you think ... either.)

    This question arose after reading about ... 'Predictability of Linear Congruential Generators'.

    LCGs are fundamentally not secure. You could not use one for a SecureRandom implementation.

    The javadoc includes references to the requirements for any SecureRandom implementation. If you have practical concerns, read the references.