9

I know that Random class generates insecure random sequences and I should prefer using SecureRandom when dealing with security. But what about ThreadLocalRandom? Is it more or less secure?

// generate a five-digit numeric confirmation code
Long code = ThreadLocalRandom.current().nextLong(1, 99999);
naXa stands with Ukraine
  • 35,493
  • 19
  • 190
  • 259

2 Answers2

10

As described in its javadoc, ThreadLocalRandom is similar to Random (i.e. not secure) but with better performance in case of concurrent access.

Instances of ThreadLocalRandom are not cryptographically secure. Consider instead using SecureRandom in security-sensitive applications.

assylias
  • 321,522
  • 82
  • 660
  • 783
8

ThreadLocalRandom is something like ThreadLocal<Random> which creates Random instance per thread. This has nothing to do with safety in cryptography context.

So the question is "what is the difference between Random and SecureRandom" implementations.

SecureRandom differs in that, it passed tests that are required for safety in cryptography. Exactly it passed tests specified by FIPS 140-2 (standard for generators used in cryptography). For more details see SecureRandom javadoc.

matoni
  • 2,479
  • 21
  • 39