Introduction
SecureRandom is Java's cryptographically strong random number generator. It was introduced in Java 1.1 in 1997 as part of the java.security package and has been refined in every major Java release since. Without a strong source of randomness, no cryptographic algorithm is secure: keys, IVs, nonces, salts, and challenges all depend on unpredictable random values. In this secure random key generation java tutorial we will generate AES keys, IVs, salts, and RSA seeds using SecureRandom and show why Math.random() is never appropriate for cryptographic material.
The importance of SecureRandom cannot be overstated. Many famous cryptographic failures have been random-generator failures. In 2008, Debian shipped a patched version of OpenSSL that stripped out almost all entropy, leaving only 15 bits of effective randomness in SSL keys for two years; thousands of HTTPS certificates had to be reissued. In 2012, a study found that 1 in 200 RSA keys on the internet shared a prime factor, because they had been generated with low-entropy RNGs during early boot. Java's SecureRandom is designed to avoid these failures by using the operating system's entropy pool directly.
What is SecureRandom?
SecureRandom is a Java class that implements a cryptographically strong pseudo-random number generator (CSPRNG). Unlike java.util.Random, which uses a linear congruential generator that is predictable from a single output, SecureRandom uses OS-level entropy sources and a cryptographically secure algorithm such as SHA1PRNG, NativePRNG, or DRBG (as specified in NIST SP 800-90A).
Three properties make SecureRandom suitable for cryptography. First, it is unpredictable: even if an attacker observes a long sequence of outputs, they cannot predict the next output. Second, it is forward-secure: if the internal state is later compromised, previously generated outputs remain unpredictable. Third, it is backtracking-resistant: if the internal state is compromised now, future outputs become unpredictable as soon as new entropy is mixed in.
The default SecureRandom implementation on Linux reads from /dev/urandom, which gathers entropy from device timings, interrupt timing, and other hardware sources. On Windows it uses CryptGenRandom. On modern JVMs you can also request a DRBG-compliant implementation that follows NIST SP 800-90A's Hash_DRBG, HMAC_DRBG, or CTR_DRBG algorithms.
Compared to Math.random(), SecureRandom is much slower but suitable for cryptographic use. Compared to java.util.Random, SecureRandom is unpredictable but thread-safe. Compared to /dev/random (which blocks when entropy is low), SecureRandom on Linux uses /dev/urandom (which does not block) and is suitable for high-throughput key generation.
How SecureRandom Works Step by Step
Let us generate a 256-bit AES key with SecureRandom.
Step 1: Create a SecureRandom instance. The simplest way is to call new SecureRandom(), which uses the highest-priority provider's default algorithm. For finer control, you can call SecureRandom.getInstance("DRBG") to request a NIST-compliant DRBG.
Step 2: Optionally seed the SecureRandom. In modern Java this is almost never needed; the OS seeds the RNG automatically. Calling setSeed() on a DRBG instance mixes in additional entropy.
Step 3: Allocate a byte array of the desired length. For a 256-bit key, use 32 bytes.
Step 4: Call nextBytes(byteArray). The SecureRandom fills the array with cryptographically strong random bytes.
Step 5: Wrap the byte array in a SecretKeySpec with the appropriate algorithm name, and you have a usable cryptographic key.
The crucial detail is that you never call setSeed() with a low-entropy value like System.currentTimeMillis() or a hardcoded constant. Seeding a SecureRandom with a predictable value defeats its purpose entirely; this is exactly the bug that broke Debian's OpenSSL.
Java Program for Secure Random Key Generation Using SecureRandom
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.HexFormat;
public class SecureRandomDemo {
public static void main(String[] args) {
SecureRandom rng = new SecureRandom();
// 1. Generate a 256-bit AES key
byte[] aesKey = new byte[32];
rng.nextBytes(aesKey);
SecretKeySpec keySpec = new SecretKeySpec(aesKey, "AES");
System.out.println("AES key (hex): " + HexFormat.of().formatHex(aesKey));
System.out.println("AES key (b64): " + Base64.getEncoder().encodeToString(aesKey));
System.out.println("Algorithm : " + keySpec.getAlgorithm());
// 2. Generate a 96-bit IV for AES-GCM (12 bytes by convention)
byte[] iv = new byte[12];
rng.nextBytes(iv);
System.out.println("\nGCM IV (b64): " + Base64.getEncoder().encodeToString(iv));
// 3. Generate a 16-byte salt for password hashing
byte[] salt = new byte[16];
rng.nextBytes(salt);
System.out.println("Salt (b64) : " + Base64.getEncoder().encodeToString(salt));
// 4. Generate a 32-byte secret token (for password reset links)
byte[] token = new byte[32];
rng.nextBytes(token);
System.out.println("Token (b64) : " + Base64.getEncoder().encodeToString(token));
// 5. Generate a random int in a range
int randomInt = rng.nextInt(1_000_000);
System.out.println("\nRandom int : " + randomInt);
// 6. Compare entropy: Math.random is predictable from a single output
long seed = System.currentTimeMillis();
java.util.Random predictable = new java.util.Random(seed);
byte[] weakBytes = new byte[16];
predictable.nextBytes(weakBytes);
System.out.println("\nWARNING: java.util.Random with seed " + seed);
System.out.println(" Weak bytes: " + HexFormat.of().formatHex(weakBytes));
System.out.println(" An attacker who knows the seed can reproduce these bytes exactly.");
System.out.println(" Never use java.util.Random or Math.random() for cryptographic material.");
// 7. Show that two SecureRandom instances produce independent sequences
SecureRandom rng2 = new SecureRandom();
byte[] otherBytes = new byte[32];
rng2.nextBytes(otherBytes);
System.out.println("\nIndependent SecureRandom outputs:");
System.out.println(" First : " + HexFormat.of().formatHex(aesKey));
System.out.println(" Second: " + HexFormat.of().formatHex(otherBytes));
boolean equal = java.util.Arrays.equals(aesKey, otherBytes);
System.out.println(" Equal? " + equal + " (should be false)");
}
}
Code Explanation Line by Line
The first line creates a new SecureRandom instance. The default constructor picks the highest-priority provider, which on most platforms is NativePRNG on Linux or Windows-PRNG on Windows. On Java 9 and later, you can also use SecureRandom.getInstance("DRBG") and configure it via SecureRandomParameters to request a NIST-compliant Hash_DRBG.
The first block generates a 32-byte AES key. We call nextBytes(byteArray), which fills the array with cryptographically strong random bytes. We then wrap the bytes in a SecretKeySpec to mark them as an AES key. The key can now be used with the standard javax.crypto.Cipher class.
The second block generates a 12-byte IV for AES-GCM. GCM uses 96-bit IVs by convention because that length allows efficient internal processing and avoids collisions with high probability. Always generate a fresh IV for every GCM encryption.
The third block generates a 16-byte salt for password hashing. The salt should be at least 16 bytes long to defeat rainbow tables. Store the salt alongside the derived key; the salt is public and does not need to be kept secret.
The fourth block generates a 32-byte secret token for password reset links. A 32-byte (256-bit) random token has enough entropy that an attacker cannot guess it even with billions of attempts. Always use SecureRandom for security tokens, never Math.random() or UUIDs (which can be predictable).
The fifth block uses nextInt to generate a random integer in a range. SecureRandom's nextInt is uniform and unpredictable, unlike java.util.Random's nextInt which is predictable from the seed.
The sixth block demonstrates the danger of using java.util.Random with a predictable seed. We seed a Random with System.currentTimeMillis(), which an attacker can guess within a small range, and use it to generate "random" bytes. An attacker who knows the seed can reproduce the bytes exactly, which means any key or IV generated this way is completely compromised. This is exactly the bug that broke Debian's OpenSSL in 2008, and it remains one of the most common cryptography implementation mistakes.
The seventh block shows that two SecureRandom instances produce independent, uncorrelated outputs. If they produced correlated outputs, an attacker who observed one instance's output could predict the other's. SecureRandom's design ensures independence through the OS entropy pool.
Sample Input and Output
AES key (hex): 4b3c2d1a0e9f8a7b6c5d4e3f2a1b0c9d8e7f6a5b4c3d2e1f0a9b8c7d6e5f4a3b AES key (b64): S8wtGg6firtMXk48KhsMnY5/a1tMPR4QCpuMXWX0ojs= Algorithm : AES GCM IV (b64): Vz3jRkL9pQ2sF8tW5nC1xQ== Salt (b64) : pQ2sF8tW5nC1xY7mB0hD6eAVz3jRkL== Token (b64) : 9F8E7D6C5B4A3Z2Y1X0W9V8U7T6S5R4Q3P2O1N0M9L8K7J6I5H4G3F2E1D0C9B== Random int : 482913 WARNING: java.util.Random with seed 1747834291847 Weak bytes: 8a7b6c5d4e3f2a1b0c9d8e7f6a5b4c3d An attacker who knows the seed can reproduce these bytes exactly. Never use java.util.Random or Math.random() for cryptographic material. Independent SecureRandom outputs: First : 4b3c2d1a0e9f8a7b6c5d4e3f2a1b0c9d... Second: 7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d... Equal? false (should be false)
The exact values will differ every run because SecureRandom is unpredictable. The crucial observations are that AES keys, IVs, salts, and tokens are all different and unpredictable, and that java.util.Random with a known seed is fully predictable.
Common Mistakes to Avoid
First, never use Math.random() or java.util.Random for cryptographic material. These generators are deterministic from a single seed and are fully predictable. Always use SecureRandom for keys, IVs, salts, tokens, and any other value that must be unpredictable.
Second, never seed SecureRandom with a low-entropy value like System.currentTimeMillis(). The OS already seeds SecureRandom with high-entropy data; manually seeding it with a low-entropy value replaces the strong seed with a weak one. If you must add entropy, use setSeed() which mixes additional entropy into the existing state.
Third, never reuse the same SecureRandom instance across many threads without synchronization. While SecureRandom is thread-safe, contention on the underlying state can hurt performance. For high-throughput applications, give each thread its own SecureRandom instance.
Fourth, never assume SecureRandom is fast enough for high-throughput use without measuring. Generating gigabytes of random data per second from a single SecureRandom instance can become a bottleneck; consider using a DRBG with periodic reseeding, or a hardware RNG.
Real-World Applications
SecureRandom generates the keys for TLS sessions, the session IDs for web applications, the IVs and nonces for AES encryption, the salts for password hashing, and the secret tokens for password reset links. UUIDs that need to be unpredictable (version 4 UUIDs) are built on top of SecureRandom. The TOTP codes generated by Google Authenticator are derived from a secret key generated with SecureRandom. Cryptocurrency wallets use SecureRandom to generate the seed phrases that protect users' funds.
The NIST SP 800-90A specification defines three approved DRBG algorithms (Hash_DRBG, HMAC_DRBG, CTR_DRBG) and one allowed but not recommended (Dual_EC_DRBG, which was backdoored by the NSA and is now deprecated). Java 9 and later support all the approved algorithms through SecureRandom.getInstanceStrong() and SecureRandom.getInstance("DRBG", params).
Conclusion
In this secure random key generation java tutorial we generated AES keys, IVs, salts, and tokens with SecureRandom, and we demonstrated why Math.random() is never acceptable for cryptographic material. SecureRandom is the foundation of every other cryptographic operation in Java, because without unpredictable randomness no key is secret, no IV is fresh, and no token is unguessable. Treat SecureRandom as carefully as you treat your secret keys.
Comments
Comments
Post a Comment