ovunccetin
ovunccetin

Reputation: 8663

Repetitive usage of Java's SecureRandom

I'm a little bit confused about the usage of SecureRandom. I need to generate n secure random numbers in a loop. Is it secure to use the same SecureRandom instance for each generation? Are there any difference between the solutions below in terms of cryptographic strength?

1) Single instance without seeding

SecureRandom sr = new SecureRandom();
for(int i = 0; i < n; ++i) sr.nextInt();

2) New instance for each generation

for(int i = 0; i < n; ++i) new SecureRandom().nextInt();

3) Single instance with seeding

SecureRandom sr = new SecureRandom()
for(int i = 0; i < n; ++i) {
    byte[] seed = sr.generateSeed(32);
    sr.setSeed(seed);
    sr.nextInt();
}

Upvotes: 8

Views: 2653

Answers (2)

Kostas Kryptos
Kostas Kryptos

Reputation: 4111

I suggest you should read this interesting article

In general, there is no need to create multiple instances of SecureRandom(), as @ElliottFrisch stated a static final is the most appropriate solution.

However, if you will use your SecureRandom for a huge sequence of random outputs, you should periodically reseed it to not allow malicious software to determine the seed and thus predict all future outputs.

Upvotes: 2

Elliott Frisch
Elliott Frisch

Reputation: 201467

Perhaps counter-intuitively the third is almost certainly the weakest, reseeding on loop iteration is a terrible idea. The second is bad, but less bad, because the SecureRandom() includes a strong default seeding strategy. As asked, the first is almost certainly the most secure because it maximizes the entropic period. I suggest you extract it to a class level constant for that reason.

private static final Random RANDOM = new SecureRandom();
// ...
// your method,
for (int i = 0; i < n; ++i) { 
    int num = RANDOM.nextInt();
}

Upvotes: 12

Related Questions