How to create an array of 20 random bytes?
Wanna quickly generate a 20-byte random array with SecureRandom? No problem:
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:
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
:
Generate predictable randomness
Sometimes you need repeatable randomness for testing or other purposes. In that case, you can seed the Random:
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:
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:
Was this article helpful?