SecureRandom is unreasonably slow or freezes the system

2.5k Views Asked by At

A java application does something like this:

SecureRandom random = new SecureRandom();
for(int i=0;i<12;i++){
   random.nextInt(19);
}

At random.nextInt() the java freezes for several minutes, seems it hangs indefinitely.
The weird part is that the behaviour is present only when I ran it through Jenkins, and I wasn’t able to reproduce the problem locally.
Also in production the code works fine.
The jenkins agent is an Ubuntu, however If I change it to a macOS agent, it works fine.
The production runs on openSUSE.
What's the magic here?

1

There are 1 best solutions below

2
Micó Papp On

Solution 1 (changing the code)

Use ThreadLocalRandom.current().nextInt() instead.

edit: ThreadLocalRandom is not "secure".
Use this only if your case is not security-sensitive.
SecureRandom is FIPS 140-2 compliant, see:

Solution 2 (without release, still secure)

Add a JVM argument to the runner: -Djava.security.egd=file:/dev/./urandom

Why is that?

So that was a little bit tricky.
SecureRandom relies on the OS random generator, which is /dev/random by default.
/dev/random relies on environment noise, such as mouse input.
If there is not enough environment noise, /dev/random is blocked by design. (actually depends on linux distro)
Boom! Locally you have system noise all the time, but on a jenkins agent maybe not.

Source