Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
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();
–
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();
–
–
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.
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.