Is SecureRandom Security Safe?

Is SecureRandom thread safe? That is, after initialization, it can access the next random number to be thread safe? Studying the source code seems to show that it is, and this error report seems to indicate that the lack of documentation as thread-safe is a javadoc problem. Has anyone confirmed that this is actually thread safe?

+82
java thread-safety
Sep 22 '09 at 17:53
source share
3 answers

Yes it is. It extends Random , which has always performed a de facto threaded implementation, and from Java 7 explicitly guarantees thread safety.

If many threads use the same SecureRandom , a problem may occur that degrades performance. On the other hand, initializing a SecureRandom instance can be relatively slow. It’s best to use a global RNG or create a new one for each thread, it will depend on your application. The ThreadLocalRandom class can be used as a template to provide a solution that supports SecureRandom .

+82
Sep 22 '09 at 18:02
source share

The current implementation of SecureRandom is thread safe, in particular, the two mutating methods nextBytes(bytes[]) and setSeed(byte[]) synchronized.

Well, as far as I could tell, all mutating methods end up being routed through these two methods, and SecureRandom overrides several methods in Random to guarantee this. This works, but can be fragile if the implementation is changed in the future.

The best solution is to manually sync first in the SecureRandom instance. This means that each call stack will acquire two locks on the same object, but usually it is very cheap on modern JVMs. That is, there is no harm in explicit synchronization. For example:

  SecureRandom rnd = ...; byte[] b = new byte[NRANDOM_BYTES]; synchronized (rnd) { rnd.nextBytes(b); } 
+8
Apr 28 '10 at 4:47 april
source share

Yes. It is completely thread safe. In fact, I would complain that the castle is too aggressive. All engineNextBytes() synchronized.

To be honest with you, I do not know if it is safe. The threading problem probably introduces more randomness :)

+1
Sep 22 '09 at 18:05
source share



All Articles