How to deal with a slow SecureRandom generator?

后端 未结 17 1124
时光说笑
时光说笑 2020-11-22 11:56

If you want a cryptographically strong random numbers in Java, you use SecureRandom. Unfortunately, SecureRandom can be very slow. If it uses

17条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 12:42

    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.

提交回复
热议问题