If you want a cryptographically strong random numbers in Java, you use SecureRandom
. Unfortunately, SecureRandom
can be very slow. If it uses
Using Java 8, I found that on Linux calling SecureRandom.getInstanceStrong()
would give me the NativePRNGBlocking
algorithm. This would often block for many seconds to generate a few bytes of salt.
I switched to explicitly asking for NativePRNGNonBlocking
instead, and as expected from the name, it no longer blocked. I have no idea what the security implications of this are. Presumably the non-blocking version can't guarantee the amount of entropy being used.
Update: Ok, I found this excellent explanation.
In a nutshell, to avoid blocking, use new SecureRandom()
. This uses /dev/urandom
, which doesn't block and is basically as secure as /dev/random
. From the post: "The only time you would want to call /dev/random is when the machine is first booting, and entropy has not yet accumulated".
SecureRandom.getInstanceStrong()
gives you the absolute strongest RNG, but it's only safe to use in situations where a bunch of blocking won't effect you.