Java SecureRandom
Java SecureRandom is the class you use whenever a random value must be impossible to guess: session IDs, password reset tokens, one-time codes, encryption keys, salts and IVs. It lives in java.security and produces cryptographically strong random numbers.
This lesson explains why java.util.Random is not safe for security, how to create and use SecureRandom, which algorithms the JDK offers, and how to build tokens, OTP codes and random passwords. It ends with a password reset token service. For everyday random numbers in games or simulations, see Java Random Numbers.
Why java.util.Random Is Not Secure
java.util.Random is a pseudo-random generator with a 48-bit internal state. Its output looks random, but every value follows from the seed by a simple formula. If an attacker sees a few outputs, they can work out the state and predict every value that follows.
The example shows the problem directly: two generators with the same seed produce exactly the same "random" sequence.
import java.util.Random;
public class PredictableRandom {
public static void main(String[] args) {
Random first = new Random(2026);
Random second = new Random(2026);
System.out.print("Generator 1: ");
for (int i = 0; i < 5; i++) {
System.out.print(first.nextInt(100) + " ");
}
System.out.print("\nGenerator 2: ");
for (int i = 0; i < 5; i++) {
System.out.print(second.nextInt(100) + " ");
}
System.out.println();
}
}
Output:
Generator 1: 99 50 97 30 49
Generator 2: 99 50 97 30 49
How it works:
- Both generators start from seed
2026, so they walk through identical states and print identical numbers. Every JDK prints this exact sequence for seed2026, which proves the values are not random at all. - Without an explicit seed,
Randomseeds itself from the clock and a counter. That makes runs look different, but the 48-bit state is still small and recoverable from its output.
| Feature | java.util.Random | java.security.SecureRandom |
|---|---|---|
| Predictable from output | Yes | No |
| Internal state | 48 bits | Large, reseeded from the OS |
| Seed source | Clock + counter | Operating system entropy |
| Speed | Very fast | Slower, still fast enough for tokens and keys |
| Use for | Games, simulations, shuffling test data | Tokens, keys, salts, IVs, OTPs, passwords |
Note:
Math.random()andThreadLocalRandomare not secure either. If a value protects an account or data, useSecureRandom.
Create a SecureRandom Object
The simplest way is new SecureRandom(). The JDK picks the best available algorithm for your operating system and seeds it automatically from OS entropy.
import java.security.SecureRandom;
public class CreateSecureRandom {
public static void main(String[] args) throws Exception {
SecureRandom defaultRandom = new SecureRandom();
System.out.println("Default algorithm: " + defaultRandom.getAlgorithm());
SecureRandom strongRandom = SecureRandom.getInstanceStrong();
System.out.println("Strong algorithm: " + strongRandom.getAlgorithm());
SecureRandom drbgRandom = SecureRandom.getInstance("DRBG");
System.out.println("DRBG algorithm: " + drbgRandom.getAlgorithm());
System.out.println("DRBG parameters: " + drbgRandom.getParameters());
}
}
Output (on Linux; Windows and macOS show different algorithm names):
Default algorithm: NativePRNG
Strong algorithm: NativePRNGBlocking
DRBG algorithm: DRBG
DRBG parameters: 128,reseed_only,null
How it works:
new SecureRandom()returns the platform default. On Linux and macOS that isNativePRNG, which reads from/dev/urandom. On Windows it is usuallyDRBG.getInstanceStrong()returns the algorithm listed in thesecurerandom.strongAlgorithmssecurity property. On Linux it reads/dev/randomand may block on systems with little entropy, so avoid it in servers.getInstance("DRBG")asks for the NIST SP 800-90A generator that every JDK includes.getParameters()shows its security strength (128 bits), its reseed capability and the personalization string (nullhere).
| Way to create | When to use |
|---|---|
new SecureRandom() | Almost always: tokens, salts, IVs, keys |
SecureRandom.getInstance("DRBG") | You need the same algorithm on every OS |
SecureRandom.getInstanceStrong() | Long-term keys on a desktop tool; can block on servers |
Note: Create one
SecureRandomand reuse it, for example in aprivate static finalfield. It is thread-safe, and creating a new one for every value wastes time.
Generate Random Bytes With nextBytes
Most security code needs raw random bytes: a 16-byte salt, a 12-byte IV, a 32-byte key. nextBytes fills an array you provide.
import java.security.SecureRandom;
import java.util.HexFormat;
public class RandomBytes {
private static final SecureRandom RANDOM = new SecureRandom();
static byte[] randomBytes(int length) {
byte[] bytes = new byte[length];
RANDOM.nextBytes(bytes);
return bytes;
}
public static void main(String[] args) {
HexFormat hex = HexFormat.of();
System.out.println("Salt (16 bytes): " + hex.formatHex(randomBytes(16)));
System.out.println("IV (12 bytes): " + hex.formatHex(randomBytes(12)));
System.out.println("Key (32 bytes): " + hex.formatHex(randomBytes(32)));
}
}
Output (different on every run):
Salt (16 bytes): 9f1c42e07ab35d6e18c0f4b2a7d93e51
IV (12 bytes): 4e7a0c91d2b8f35a6c1e09d4
Key (32 bytes): c3a91f0e5b7d2846a0e9f13c7b52d8e4196af07c3e5b2d81a49f6c0e7d31b2a5
How it works:
nextBytesoverwrites every byte of the array with random data.HexFormat(Java 17+) prints the bytes as hex so you can see them. Each run prints new values.- These are the same sizes used in Java Cryptography Basics: a 16-byte salt for PBKDF2, a 12-byte IV for AES-GCM and a 32-byte AES-256 key.
Note: For AES keys,
KeyGeneratoris still the cleaner choice, because it returns a properSecretKeyobject. Internally it also usesSecureRandom.
Random Numbers in a Range
SecureRandom extends Random, so all the familiar methods work: nextInt(bound), nextLong(), nextDouble() and nextBoolean(). Since Java 17 it also implements RandomGenerator, which adds nextInt(origin, bound).
import java.security.SecureRandom;
public class SecureRanges {
public static void main(String[] args) {
SecureRandom random = new SecureRandom();
int dieRoll = random.nextInt(1, 7); // 1 to 6
int percent = random.nextInt(101); // 0 to 100
long bigNumber = random.nextLong();
double fraction = random.nextDouble(); // 0.0 (inclusive) to 1.0 (exclusive)
boolean coin = random.nextBoolean();
System.out.println("Die roll: " + dieRoll);
System.out.println("Percent: " + percent);
System.out.println("Long: " + bigNumber);
System.out.printf("Fraction: %.4f%n", fraction);
System.out.println("Heads? " + coin);
// Stream of 5 random numbers between 1000 and 9999
System.out.print("Stream: ");
random.ints(5, 1000, 10_000).forEach(n -> System.out.print(n + " "));
System.out.println();
}
}
Output (different on every run):
Die roll: 4
Percent: 67
Long: -3816244012971550312
Fraction: 0.2874
Heads? true
Stream: 7312 1049 5586 9921 2730
How it works:
nextInt(1, 7)returns a value from 1 up to 6. The upper bound is always exclusive.nextInt(101)returns 0 to 100. These methods have no "modulo bias": every value in the range is equally likely.ints(5, 1000, 10_000)returns anIntStreamof five numbers, handy for generating several values at once.
Generate Secure Tokens for URLs and Sessions
A session ID or API token needs enough randomness that nobody can guess it. 32 random bytes (256 bits) is a safe size. Base64 URL encoding turns the bytes into text that is safe in URLs, cookies and headers.
import java.security.SecureRandom;
import java.util.Base64;
import java.util.HashSet;
import java.util.Set;
public class SecureTokens {
private static final SecureRandom RANDOM = new SecureRandom();
private static final Base64.Encoder URL_ENCODER = Base64.getUrlEncoder().withoutPadding();
static String newToken(int byteLength) {
byte[] bytes = new byte[byteLength];
RANDOM.nextBytes(bytes);
return URL_ENCODER.encodeToString(bytes);
}
public static void main(String[] args) {
String sessionId = newToken(32);
System.out.println("Session ID: " + sessionId);
System.out.println("Length: " + sessionId.length() + " characters");
// Generate many tokens and check for duplicates
Set<String> tokens = new HashSet<>();
for (int i = 0; i < 100_000; i++) {
tokens.add(newToken(32));
}
System.out.println("Unique tokens out of 100000: " + tokens.size());
}
}
Output (the token differs on every run):
Session ID: rX3m9Qe_0kT2uZcV8bLwYp4HnA1sDf6GjKq7RtEoMiU
Length: 43 characters
Unique tokens out of 100000: 100000
How it works:
getUrlEncoder()uses-and_instead of+and/, so the token needs no escaping in a URL.withoutPadding()drops the trailing=.- 32 bytes become 43 characters. With 2^256 possible values, guessing a token is not realistic, and duplicates practically never happen, as the 100,000-token check shows.
Note: Do not build tokens from
UUID.randomUUID()and assume more security than it has. A random UUID usesSecureRandom, but only 122 of its 128 bits are random. It is fine as an ID, but a 32-byte token is the better choice for secrets.
One-Time Codes and Random Passwords
Some values must use a limited alphabet: a 6-digit OTP sent by SMS, or a password that people can type. Pick each character with nextInt(alphabet.length()), which gives every character an equal chance.
import java.security.SecureRandom;
public class OtpAndPasswords {
private static final SecureRandom RANDOM = new SecureRandom();
private static final String UPPER = "ABCDEFGHJKLMNPQRSTUVWXYZ"; // no I or O
private static final String LOWER = "abcdefghijkmnopqrstuvwxyz"; // no l
private static final String DIGITS = "23456789"; // no 0 or 1
private static final String SYMBOLS = "!@#$%&*?";
// 6-digit code, leading zeros kept
static String otp() {
return String.format("%06d", RANDOM.nextInt(1_000_000));
}
static char pick(String alphabet) {
return alphabet.charAt(RANDOM.nextInt(alphabet.length()));
}
// At least one character from each group, then shuffled
static String password(int length) {
String all = UPPER + LOWER + DIGITS + SYMBOLS;
char[] chars = new char[length];
chars[0] = pick(UPPER);
chars[1] = pick(LOWER);
chars[2] = pick(DIGITS);
chars[3] = pick(SYMBOLS);
for (int i = 4; i < length; i++) {
chars[i] = pick(all);
}
// Fisher-Yates shuffle so the guaranteed characters are not always first
for (int i = length - 1; i > 0; i--) {
int j = RANDOM.nextInt(i + 1);
char temp = chars[i];
chars[i] = chars[j];
chars[j] = temp;
}
return new String(chars);
}
public static void main(String[] args) {
System.out.println("OTP codes: " + otp() + ", " + otp() + ", " + otp());
System.out.println("Password (12): " + password(12));
System.out.println("Password (16): " + password(16));
}
}
Output (different on every run):
OTP codes: 048213, 731905, 600472
Password (12): q7&HtZ9mWkx#
Password (16): Ra4!vNe8@pYjs2Kd
How it works:
nextInt(1_000_000)returns 0 to 999,999, and%06dpads with zeros so48213becomes048213. Every code is equally likely.- The alphabets leave out characters that look alike (
I,l,1,O,0), which reduces typing mistakes. - The first four characters guarantee one of each group. The Fisher-Yates shuffle then moves them to random positions, using
SecureRandomagain so the order is unpredictable.
Seeding SecureRandom Correctly
You do not need to seed SecureRandom; it seeds itself from the operating system the first time you use it. Calling setSeed adds extra data to that seed rather than replacing it on most algorithms. Creating it with a fixed seed is a common mistake, as this example shows with a deterministic DRBG used only for tests.
import java.security.DrbgParameters;
import java.security.SecureRandom;
import java.util.HexFormat;
public class SeedingSecureRandom {
public static void main(String[] args) throws Exception {
// Normal use: self-seeded, different every time
SecureRandom normal = new SecureRandom();
byte[] a = new byte[8];
normal.nextBytes(a);
System.out.println("Self-seeded: " + HexFormat.of().formatHex(a));
// Extra seed material is mixed in; output is still unpredictable
normal.setSeed(42L);
normal.nextBytes(a);
System.out.println("After setSeed(42): " + HexFormat.of().formatHex(a));
// DRBG with prediction resistance: reseeds from the OS before every call
SecureRandom reseeding = SecureRandom.getInstance("DRBG",
DrbgParameters.instantiation(256, DrbgParameters.Capability.PR_AND_RESEED, null));
reseeding.nextBytes(a);
System.out.println("PR DRBG (256-bit): " + HexFormat.of().formatHex(a));
System.out.println("Parameters: " + reseeding.getParameters());
}
}
Output (values differ on every run):
Self-seeded: 5ac91e03b7f2d468
After setSeed(42): e20b7c9f41a8d356
PR DRBG (256-bit): 91d4f06a2ce83b7f
Parameters: 256,pr_and_reseed,null
How it works:
- The self-seeded generator gives fresh bytes each run without any setup.
setSeed(42L)on an already-seededSecureRandomadds 42 to its existing seed. The output stays unpredictable, so calling it is harmless but unnecessary.DrbgParameters.instantiation(256, PR_AND_RESEED, null)asks for a 256-bit-strength DRBG with prediction resistance: it pulls fresh entropy from the OS before every request. Use it for very long-lived keys.
Note: Never use
SecureRandom.getInstance("SHA1PRNG")with a fixed seed set before first use. That algorithm then becomes fully deterministic, and old tutorials that do this produce predictable "random" keys.
Real-World Example: Password Reset Token Service
A password reset link must contain a token that cannot be guessed, expires quickly and works only once. The service below creates such tokens with SecureRandom, stores only their SHA-256 hashes (so a database leak does not expose working links), and checks them in constant time.
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.time.Duration;
import java.time.Instant;
import java.util.Base64;
import java.util.HexFormat;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class PasswordResetService {
private static final SecureRandom RANDOM = new SecureRandom();
private static final Duration TOKEN_LIFETIME = Duration.ofMinutes(15);
// What the database stores: hash of the token -> who it belongs to and when it expires
record ResetRecord(String email, Instant expiresAt) {}
private final Map<String, ResetRecord> storedTokens = new ConcurrentHashMap<>();
private static String sha256(String token) {
try {
byte[] hash = MessageDigest.getInstance("SHA-256").digest(token.getBytes(StandardCharsets.UTF_8));
return HexFormat.of().formatHex(hash);
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
// Returns the link to email; the raw token is never stored
String createResetLink(String email, Instant now) {
byte[] tokenBytes = new byte[32];
RANDOM.nextBytes(tokenBytes);
String token = Base64.getUrlEncoder().withoutPadding().encodeToString(tokenBytes);
storedTokens.put(sha256(token), new ResetRecord(email, now.plus(TOKEN_LIFETIME)));
return "https://gocourse.in/reset?token=" + token;
}
// Returns the email if the token is valid; removes it so it works only once
String redeem(String token, Instant now) {
String tokenHash = sha256(token);
ResetRecord record = null;
for (Map.Entry<String, ResetRecord> entry : storedTokens.entrySet()) {
// constant-time comparison of the hashes
if (MessageDigest.isEqual(entry.getKey().getBytes(StandardCharsets.UTF_8),
tokenHash.getBytes(StandardCharsets.UTF_8))) {
record = entry.getValue();
}
}
if (record == null) {
return "INVALID: unknown or already used token";
}
storedTokens.remove(tokenHash);
if (now.isAfter(record.expiresAt())) {
return "INVALID: token expired";
}
return "OK: reset password for " + record.email();
}
public static void main(String[] args) {
PasswordResetService service = new PasswordResetService();
Instant now = Instant.parse("2026-11-17T10:00:00Z");
String link = service.createResetLink("asha@example.com", now);
String token = link.substring(link.indexOf("token=") + 6);
System.out.println("Email link: " + link.substring(0, 50) + "...");
System.out.println("Stored value is a hash? " + !service.storedTokens.containsKey(token));
System.out.println("Use after 5 min: " + service.redeem(token, now.plus(Duration.ofMinutes(5))));
System.out.println("Use again: " + service.redeem(token, now.plus(Duration.ofMinutes(6))));
String lateLink = service.createResetLink("ravi@example.com", now);
String lateToken = lateLink.substring(lateLink.indexOf("token=") + 6);
System.out.println("Use after 20 min: " + service.redeem(lateToken, now.plus(Duration.ofMinutes(20))));
System.out.println("Guessed token: " + service.redeem("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", now));
}
}
Output (the token in the link differs on every run):
Email link: https://gocourse.in/reset?token=Z1v8qN3xTk0bWm...
Stored value is a hash? true
Use after 5 min: OK: reset password for asha@example.com
Use again: INVALID: unknown or already used token
Use after 20 min: INVALID: token expired
Guessed token: INVALID: unknown or already used token
How it works:
- Unguessable token.
createResetLinkfills 32 bytes from a sharedSecureRandomand encodes them as a 43-character URL-safe string. - Store only the hash. The map key is the SHA-256 hash of the token. Someone who reads the stored data cannot rebuild a working link, just as servers store password hashes instead of passwords.
- Single use.
redeemremoves the record as soon as it is found, so the second attempt fails. - Expiry. Each record keeps an
expiresAttime 15 minutes after creation. Passingnowas a parameter makes the expiry easy to demonstrate and to test. - Constant-time check.
MessageDigest.isEqualcompares the hashes without stopping at the first different byte, so response timing reveals nothing about the stored value. - Guessing fails. A made-up token hashes to a value that is not stored. With 2^256 possible tokens, guessing a real one is not practical.
In a real application the map would be a database table, and the link would be sent by email instead of printed.