Explain Codes LogoExplain Codes Logo

How to deal with a slow SecureRandom generator?

java
performance-issues
security-best-practices
entropy-management
Nikita BarsukovbyNikita Barsukov·Feb 16, 2025
TLDR

Boost SecureRandom generation time in a flash by calling on the quicker, non-blocking source /dev/urandom through new SecureRandom(). Ensure an agile SecureRandom initialization by seeding it asynchronously.

SecureRandom srFast = new SecureRandom(); // For when you need fast. Real fast.

JVM-level configuration can also give you a leg up:

-Djava.security.egd=file:/dev/./urandom //The need for speed

Walking the urandom path

The /dev/urandom route is quick and dirty by comparison, but knowing how to dress for the journey is vital to continue keeping your secrets safe. When you call SecureRandom without a bodyguard (arguments), it naturally follows this path. But if you require stronger entropy, like when dealing with crypto operations, you'll want to inform SecureRandom about your seed source.

byte[] seed = someSecureSource.getBytes(); srFast.setSeed(seed); //Crank up that entropy!

Breaking free from entropy's grasp

Cut the cord with blocking by ensuring entropy collection isn't halting your progress. Keep the setSeed() method busy in the background to keep re-seeding SecureRandom without a hitch.

Root of the problem

Get serious: cruises through some commonly run into performance issues with Big 'S' - SecureRandom:

  • Where's the Party: /dev/random is waiting for an invite, while /dev/urandom simply gatecrashes.
  • Algorithm Mixers: "SecureRandom.getInstance('SHA1PRNG')" is always up for a quick dance.
  • Little Bugs with Big Impact: Send a nod to Java Bug 6202721 when you have a SecRandom performance hangover.
SecureRandom srFastButSafe = SecureRandom.getInstance("SHA1PRNG"); //Fast, Secure. Pick two!

Alternate routes

We also have some stealthy paths up our sleeve:

  • Non-crypto tasks, shake hands with non-secure seeds for speed runs.
  • Sometimes, using Uncommon Maths is like trying to make a snail sprint. SecureRandom has its own pace.

Striking a balance

In a world of performance over security, walking the tightrope with your entropy source choice is key:

  • /dev/random vs /dev/urandom: Random is secure but a bit introverted, while urandom is life-of-the-party but has loose lips.
  • Seeding strategies: Keep the entropy quality high and the party going by seeding on the go.