SecureRandom, PBKDF2 & Password-Safe Key Derivation in Java
Security code needs two things that ordinary Java APIs do not provide: random values an attacker cannot predict, and password hashes that are slow to guess. SecureRandom covers the first; PBKDF2 with a salt and a high iteration count covers the second.
Contents
Random numbers for security
A pseudorandom number generator (PRNG) expands a small internal state into a long sequence of numbers that look random. Ordinary PRNGs are designed for speed and good statistical distribution, for simulations, tests and games. A cryptographically secure PRNG adds a much stronger property: even after seeing any amount of its output, nobody can predict the next value or recover earlier ones. Its state is seeded from unpredictable events collected by the operating system, such as interrupt timings and hardware random number instructions.
Security code needs the second kind wherever a value must be unguessable: session IDs, password-reset tokens, API keys, salts, IVs and keys. Java has both kinds:
| Class | Since | Secure? | Best for |
|---|---|---|---|
java.util.RandomMath.random() | 1.0 | No | Legacy code; reproducible sequences from a seed |
ThreadLocalRandom | 7 | No | Fast random numbers in concurrent code |
SplittableRandom | 8 | No | Parallel streams and simulations |
RandomGenerator | 17 (JEP 356) | No | Choosing a modern statistical algorithm by name |
SecureRandom | 1.1 | Yes | Tokens, keys, salts, IVs |
SecureRandom.getInstance("DRBG") | 9 (JEP 273) | Yes | NIST SP 800-90A generators with configurable strength |
The second half of the page covers the other place where security code must be deliberately expensive: hashing passwords. All programs use only the JDK and were run on JDK 21 on Linux.
Why java.util.Random is not enough
java.util.RandomnextInt()
import java.security.SecureRandom;
import java.util.Base64;
import java.util.Random;
public class PredictRandom {
// java.util.Random is a 48-bit linear congruential generator
static final long MULT = 0x5DEECE66DL;
static final long ADD = 0xBL;
static final long MASK = (1L << 48) - 1;
public static void main(String[] args) {
// A "secret" token generator seeded from the clock
Random victim = new Random(System.nanoTime());
int first = victim.nextInt();
int second = victim.nextInt();
int third = victim.nextInt();
// Attacker sees only the first two outputs and searches the 16 hidden bits
Long state = null;
for (long low = 0; low < (1L << 16); low++) {
long candidate = ((long) first << 16) + low;
long next = (candidate * MULT + ADD) & MASK;
if ((int) (next >>> 16) == second) {
state = next;
break;
}
}
long predictedState = (state * MULT + ADD) & MASK;
int predicted = (int) (predictedState >>> 16);
System.out.println("attacker predicted the third value correctly: "
+ (predicted == third));
// SecureRandom: unpredictable, seeded by the operating system
SecureRandom sr = new SecureRandom();
System.out.println("SecureRandom algorithm here: " + sr.getAlgorithm());
byte[] token = new byte[32];
sr.nextBytes(token);
String t = Base64.getUrlEncoder().withoutPadding().encodeToString(token);
System.out.println("256-bit URL-safe token has " + t.length() + " characters");
}
}
Output:
attacker predicted the third value correctly: true
SecureRandom algorithm here: NativePRNG
256-bit URL-safe token has 43 characters
- The prediction was correct, and it succeeded on all 20 runs while preparing this page. A seed from
does not help, because the attack recovers the internal state directly. The same applies toSystem.nanoTime() andMath.random() , which are also designed for speed, not secrecy.ThreadLocalRandom uses the operating system's entropy (NativePRNG, backed bySecureRandom , on Linux and macOS). Use it for session IDs, reset tokens, API keys, salts and IVs./dev/urandom- 32 random bytes give a 256-bit token; Base64 URL encoding without padding makes it 43 characters, safe for URLs and headers.
new SecureRandom()SecureRandom.getInstanceStrong()
SecureRandom algorithms and generators
SecureRandomMessageDigestnew SecureRandom()RandomGenerator
import java.security.DrbgParameters;
import java.security.SecureRandom;
import java.security.Security;
import java.util.Base64;
import java.util.TreeSet;
import java.util.random.RandomGenerator;
import java.util.random.RandomGeneratorFactory;
public class Generators {
public static void main(String[] args) throws Exception {
SecureRandom def = new SecureRandom();
System.out.println("new SecureRandom(): " + def.getAlgorithm() + " from "
+ def.getProvider().getName());
SecureRandom strong = SecureRandom.getInstanceStrong();
System.out.println("getInstanceStrong(): " + strong.getAlgorithm()
+ " (securerandom.strongAlgorithms = "
+ Security.getProperty("securerandom.strongAlgorithms") + ")");
System.out.println("SecureRandom algorithms: "
+ new TreeSet<>(Security.getAlgorithms("SecureRandom")));
// DRBG (Java 9, JEP 273) with explicit strength and prediction resistance
SecureRandom drbg = SecureRandom.getInstance("DRBG",
DrbgParameters.instantiation(256, DrbgParameters.Capability.PR_AND_RESEED, null));
System.out.println("DRBG: " + drbg.getParameters());
// Seeding a SecureRandom does not make it reproducible (NativePRNG mixes in OS entropy)
SecureRandom a = new SecureRandom();
SecureRandom b = new SecureRandom();
a.setSeed(42);
b.setSeed(42);
System.out.println("two NativePRNG seeded with 42 agree: "
+ (a.nextLong() == b.nextLong()));
// A token for a password-reset link
byte[] token = new byte[32];
def.nextBytes(token);
System.out.println("256-bit token: " + Base64.getUrlEncoder().withoutPadding()
.encodeToString(token).length() + " URL-safe characters");
// Java 17's RandomGenerator family: fast and well distributed, but not secure
TreeSet<String> names = new TreeSet<>();
RandomGeneratorFactory.all().forEach(f -> names.add(f.name()
+ (f.isStochastic() ? " (stochastic)" : "")));
System.out.println("RandomGenerator algorithms: " + names);
System.out.println("RandomGenerator.getDefault(): " + RandomGenerator.getDefault()
.getClass().getSimpleName());
}
}
Output:
new SecureRandom(): NativePRNG from SUN
getInstanceStrong(): NativePRNGBlocking (securerandom.strongAlgorithms = NativePRNGBlocking:SUN,DRBG:SUN)
SecureRandom algorithms: [DRBG, NATIVEPRNG, NATIVEPRNGBLOCKING, NATIVEPRNGNONBLOCKING, SHA1PRNG]
DRBG: 256,pr_and_reseed,null
two NativePRNG seeded with 42 agree: false
256-bit token: 43 URL-safe characters
RandomGenerator algorithms: [L128X1024MixRandom, L128X128MixRandom, L128X256MixRandom, L32X64MixRandom, L64X1024MixRandom, L64X128MixRandom, L64X128StarStarRandom, L64X256MixRandom, Random, SecureRandom (stochastic), SplittableRandom, Xoroshiro128PlusPlus, Xoshiro256PlusPlus]
RandomGenerator.getDefault(): L32X64MixRandom
chosenew SecureRandom() , which reads the kernel's random source.NativePRNG returnedgetInstanceStrong() , taken from theNativePRNGBlocking security property; it readssecurerandom.strongAlgorithms , which on older Linux kernels could block for a long time when the system had collected little entropy./dev/random- A DRBG can be created with an explicit security strength (256 bits here) and prediction resistance, which reseeds from the operating system before every request. That is what standards such as FIPS 140 ask for; for ordinary applications the default is already strong.
- Two
instances seeded with the same value 42 produced different numbers:NativePRNG adds to the operating system's entropy instead of replacing it. Code that seeds asetSeed to get reproducible test data does not get it with this algorithm. (SecureRandom seeded before first use is deterministic, which has been a source of real vulnerabilities.)SHA1PRNG - The Java 17
family lists 13 algorithms, fromRandomGenerator , the default, toL32X64MixRandom . OnlyXoshiro256PlusPlus is marked stochastic, meaning it draws on real entropy; all the others are predictable once their state is known.SecureRandom
Random numbers in a range, and the cost of security
Turning random bits into a number from 0 to 99 is a common place for subtle bias. The program shows two traps in the hand-written approach, then measures how many random int
import java.security.SecureRandom;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.IntSupplier;
public class RangesAndSpeed {
public static void main(String[] args) throws Exception {
// Trap 1: Math.abs(nextInt()) % n can be negative
System.out.println("Math.abs(Integer.MIN_VALUE) = " + Math.abs(Integer.MIN_VALUE));
System.out.println("Math.abs(Integer.MIN_VALUE) % 10 = "
+ Math.abs(Integer.MIN_VALUE) % 10);
// Trap 2: % n is biased when n does not divide the range evenly
// (shown with a byte, 256 values, reduced to 0..99)
int[] counts = new int[100];
SecureRandom rnd = new SecureRandom();
byte[] b = new byte[1];
for (int i = 0; i < 1000000; i++) {
rnd.nextBytes(b);
counts[(b[0] & 0xFF) % 100]++;
}
System.out.printf("byte %% 100: value 10 came up %,d times, value 90 %,d times%n",
counts[10], counts[90]);
int[] fair = new int[100];
for (int i = 0; i < 1000000; i++) {
fair[rnd.nextInt(100)]++;
}
System.out.printf("nextInt(100): value 10 came up %,d times, value 90 %,d times%n",
fair[10], fair[90]);
// Rough speed: ints per second for each generator (best of 3)
Random random = new Random(1);
SecureRandom secure = new SecureRandom();
SecureRandom drbg = SecureRandom.getInstance("DRBG");
String[] names = {"java.util.Random", "ThreadLocalRandom", "SecureRandom (NativePRNG)",
"SecureRandom (DRBG)"};
IntSupplier[] gens = {random::nextInt, () -> ThreadLocalRandom.current().nextInt(),
secure::nextInt, drbg::nextInt};
for (int g = 0; g < gens.length; g++) {
long best = Long.MAX_VALUE;
int sink = 0;
for (int run = 0; run < 4; run++) {
long t0 = System.nanoTime();
for (int i = 0; i < 1000000; i++) {
sink += gens[g].getAsInt();
}
if (run > 0) {
best = Math.min(best, System.nanoTime() - t0);
}
}
System.out.printf("%-26s %,6d million ints/s%s%n", names[g],
Math.round(1000000 / (best / 1e9) / 1e6), sink == 42 ? " " : "");
}
}
}
Output:
Math.abs(Integer.MIN_VALUE) = -2147483648
Math.abs(Integer.MIN_VALUE) % 10 = -8
byte % 100: value 10 came up 11,707 times, value 90 7,846 times
nextInt(100): value 10 came up 9,917 times, value 90 10,001 times
java.util.Random 113 million ints/s
ThreadLocalRandom 555 million ints/s
SecureRandom (NativePRNG) 12 million ints/s
SecureRandom (DRBG) 3 million ints/s
is still negative, because +2,147,483,648 does not fit in anMath.abs(Integer.MIN_VALUE) . Soint returns -8 about once in four billion calls, enough to crash a busy server occasionally.Math.abs(rnd.nextInt()) % 10- Reducing a byte with
made values 0 to 55 noticeably more likely than 56 to 99: 256 values do not divide evenly into 100, so the low values get three chances and the high values two. So 10 came up about one and a half times as often as 90, close to the expected 3 to 2. For a PIN or a lottery, that bias is a vulnerability.% 100 rejects and redraws the values that would cause bias, and gave about 10,000 each. Always usenextInt(100) ,nextInt(bound) ornextLong(bound) .ints(n, origin, bound) was several times slower thanSecureRandom and far slower thanjava.util.Random , yet still delivered millions of values per second. That is plenty for tokens and keys; only simulations that need billions of numbers have a reason to prefer the fast generators.ThreadLocalRandom
Hashing passwords with PBKDF2
A fast hash such as SHA-256 lets an attacker who steals the password table try billions of guesses per second (see
- the salt, 16 random bytes per user, makes equal passwords hash differently and defeats precomputed tables;
- the iteration count repeats HMAC-SHA256 hundreds of thousands of times, so each guess costs as much as each legitimate login. 600,000 is the current OWASP recommendation for PBKDF2-HMAC-SHA256.
The program first checks the JDK's PBKDF2 against the test vector published in RFC 7914, then stores a password, verifies a correct and a nearly correct guess, and hashes the same password a second time.
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.HexFormat;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
public class Pbkdf2 {
static final int ITERATIONS = 600000; // OWASP guidance for PBKDF2-HMAC-SHA256
static byte[] derive(char[] password, byte[] salt, int iterations, int bits)
throws Exception {
PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, bits);
try {
return SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256")
.generateSecret(spec).getEncoded();
} finally {
spec.clearPassword();
}
}
// Stored form: algorithm$iterations$salt$hash
static String hash(char[] password) throws Exception {
byte[] salt = new byte[16];
new SecureRandom().nextBytes(salt);
byte[] h = derive(password, salt, ITERATIONS, 256);
Base64.Encoder b64 = Base64.getEncoder().withoutPadding();
return "pbkdf2-sha256$" + ITERATIONS + "$" + b64.encodeToString(salt) + "$"
+ b64.encodeToString(h);
}
static boolean verify(char[] password, String stored) throws Exception {
String[] parts = stored.split("\\$");
int iterations = Integer.parseInt(parts[1]);
byte[] salt = Base64.getDecoder().decode(parts[2]);
byte[] expected = Base64.getDecoder().decode(parts[3]);
byte[] actual = derive(password, salt, iterations, expected.length * 8);
return MessageDigest.isEqual(expected, actual);
}
public static void main(String[] args) throws Exception {
// RFC 7914 section 11 test vector: PBKDF2-HMAC-SHA256("passwd", "salt", 1, 64 bytes)
byte[] kat = derive("passwd".toCharArray(), "salt".getBytes(StandardCharsets.UTF_8),
1, 512);
String expected = "55ac046e56e3089fec1691c22544b605f94185216dde0465e68b9d57c20dacbc"
+ "49ca9cccf179b645991664b39d77ef317c71b845b1e30bd509112041d3a19783";
System.out.println("RFC 7914 test vector matches: "
+ HexFormat.of().formatHex(kat).equals(expected));
long start = System.nanoTime();
String stored = hash("correct horse battery staple".toCharArray());
long ms = (System.nanoTime() - start) / 1000000;
System.out.println("stored: " + stored.substring(0, stored.indexOf('$', 22)) + "$...");
System.out.println("one hash took over 100 ms: " + (ms > 100));
System.out.println("right password verifies: "
+ verify("correct horse battery staple".toCharArray(), stored));
System.out.println("wrong password verifies: "
+ verify("correct horse battery stapler".toCharArray(), stored));
String other = hash("correct horse battery staple".toCharArray());
System.out.println("same password hashed twice gives the same string: "
+ stored.equals(other));
}
}
Output (the salt is random):
RFC 7914 test vector matches: true
stored: pbkdf2-sha256$600000$jsHzioBRt3Z3iP+0/eFfkQ$...
one hash took over 100 ms: true
right password verifies: true
wrong password verifies: false
same password hashed twice gives the same string: false
- The stored string records the algorithm, the iteration count and the salt alongside the hash. Verification reads them back, so you can raise the iteration count later for new hashes and still verify old ones.
- One hash took over 100 ms. That is fine for a login, but it means one CPU core can test only a few guesses per second instead of millions.
- A one-letter difference fails, and hashing the same password twice gives different strings because the salts differ.
- Passwords are passed as
andchar[] wipes the copy insideclearPassword() , so the password does not linger in memory as an immutablePBEKeySpec . (The demo starts from string literals for brevity.)String - The comparison uses
, which runs in constant time.MessageDigest.isEqual
Choosing the iteration count
The iteration count is a dial between login speed and attack cost, and the right setting depends on your hardware. The program times one PBKDF2-HMAC-SHA256 hash at four iteration counts after a warm-up, which turns directly into guesses per second for an attacker with the same CPU. It then derives an AES key from a password and checks that clearPassword
import java.security.SecureRandom;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
public class Pbkdf2Cost {
static long micros(int iterations, byte[] salt) throws Exception {
SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
long best = Long.MAX_VALUE;
for (int run = 0; run < 4; run++) {
PBEKeySpec spec = new PBEKeySpec("correct horse".toCharArray(), salt, iterations,
256);
long t0 = System.nanoTime();
f.generateSecret(spec).getEncoded();
spec.clearPassword();
best = Math.min(best, System.nanoTime() - t0);
}
return best / 1000;
}
public static void main(String[] args) throws Exception {
byte[] salt = new byte[16];
new SecureRandom().nextBytes(salt);
micros(600000, salt); // warm up the JIT
System.out.println("PBKDF2-HMAC-SHA256, one hash, best of 4 (one core):");
for (int it : new int[] {1000, 10000, 100000, 600000}) {
long us = micros(it, salt);
System.out.printf(" %,9d iterations: %8.1f ms -> about %,7d guesses/s per core%n",
it, us / 1000.0, 1000000 / us);
}
// The same function derives an AES key from a password
SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
PBEKeySpec spec = new PBEKeySpec("correct horse".toCharArray(), salt, 600000, 256);
byte[] aesKey = f.generateSecret(spec).getEncoded();
spec.clearPassword();
System.out.println("derived AES key: " + aesKey.length * 8 + " bits");
try {
spec.getPassword();
} catch (IllegalStateException e) {
System.out.println("after clearPassword(): " + e.getMessage());
}
}
}
Output of the iteration timing run:
PBKDF2-HMAC-SHA256, one hash, best of 4 (one core):
1,000 iterations: 0.2 ms -> about 4,566 guesses/s per core
10,000 iterations: 1.8 ms -> about 549 guesses/s per core
100,000 iterations: 18.1 ms -> about 55 guesses/s per core
600,000 iterations: 107.9 ms -> about 9 guesses/s per core
derived AES key: 256 bits
after clearPassword(): password has been cleared
- The cost grew in proportion to the iteration count: ten times the iterations, ten times the time. At OWASP's 600,000 iterations, one hash took around a tenth of a second here, so one core could test only a handful of passwords per second.
- Attackers use GPUs, which compute PBKDF2-HMAC-SHA256 thousands of times faster than one CPU core, so the margin is smaller than these numbers suggest. That is why memory-hard functions such as Argon2id and scrypt, which GPUs handle poorly, are preferred where they are available.
- A login server pays this cost on every login, so measure on production hardware and pick the highest count that keeps logins acceptable. Store the count with each hash, as the stored format above does, and re-hash a user's password at the next successful login when the count is raised.
- The same call derived a 256-bit AES key from a password. After
,clearPassword() throwsgetPassword() , which confirms that the spec's copy was wiped.IllegalStateException
Choosing a password hash
| Algorithm | In the JDK | Notes |
|---|---|---|
| PBKDF2-HMAC-SHA256 | Yes | FIPS-approved; needs a high iteration count because GPUs compute it efficiently |
| bcrypt | No (Spring Security, jBCrypt) | Widely used; input limited to 72 bytes |
| scrypt | No (Bouncy Castle) | Memory-hard, which makes GPU attacks expensive |
| Argon2id | No (Bouncy Castle, Password4j) | Winner of the Password Hashing Competition; OWASP's first choice |
PBKDF2 can also turn a password into an AES key: derive 256 bits with a stored salt and use them as a SecretKeySpec