Explain Codes LogoExplain Codes Logo

How to create an array of 20 random bytes?

java
randomness
security
performance
Alex KataevbyAlex Kataev·Oct 22, 2024
TLDR

Wanna quickly generate a 20-byte random array with SecureRandom? No problem:

byte[] randBytes = new byte[20]; //Here's the star of the party: Mr. SecureRandom! new SecureRandom().nextBytes(randBytes);

This one-liner first creates a byte array named randBytes and then fills it with secure random bytes using nextBytes. Simple, concise, and ready-to-rock'n'roll.

Alternatives and considerations

In the Java world, there are always multiple paths up the mountain. Let's look at some of the popular methods to generate an array of random bytes.

Utilize java.util.Random

This Swiss Army Knife has been in the toolbox since the very early days of Java. You can put Random to work like so:

byte[] randomBytes = new byte[20]; //Random doing its random thing new Random().nextBytes(randomBytes);

Just keep in mind, Random took an "Intro to Randomness" course, not "Advanced Crypto". It's predictable, so don't rely on it for cryptographic security.

When threading matters

Got a multi-threaded challenge on your hands? Summon ThreadLocalRandom:

byte[] randomBytes = new byte[20]; //ThreadLocalRandom — a way to surprise each thread on its own. ThreadLocalRandom.current().nextBytes(randomBytes);

Generate predictable randomness

Sometimes you need repeatable randomness for testing or other purposes. In that case, you can seed the Random:

byte[] randomBytes = new byte[20]; //Predictable randomness. Yes, you read that correctly. new Random(System.currentTimeMillis()).nextBytes(randomBytes);

However, secure random numbers deserve their privacy. So, let SecureRandom generate its own unique seed.

Go extra secure with your bytes

When the stakes are high, resort to cryptographically secure randomness:

SecureRandom secureRandom = SecureRandom.getInstanceStrong(); byte[] secureBytes = new byte[20]; //Level up your security with SecureRandom secureRandom.nextBytes(secureBytes);

Using SecureRandom is like upping your padlock to the Fort Knox level!

Beware of SecureRandom's power

SecureRandom may be secure, but its thirst for CPU can give your app a performance hangover. Know when to use it, and when a little less security would save on the aspirin.

Third-party to the rescue

With the Apache Commons Lang library, you can get your random bytes in a flash:

//Apache Commons Lang making quick work of it! byte[] randomBytes = RandomUtils.nextBytes(20);