Java SecureRandom

Su Suriya Ravichandran Updated 18 Nov 2026
12 min read ·Lesson 248 of 306

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 seed 2026, which proves the values are not random at all.
  • Without an explicit seed, Random seeds 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.
Featurejava.util.Randomjava.security.SecureRandom
Predictable from outputYesNo
Internal state48 bitsLarge, reseeded from the OS
Seed sourceClock + counterOperating system entropy
SpeedVery fastSlower, still fast enough for tokens and keys
Use forGames, simulations, shuffling test dataTokens, keys, salts, IVs, OTPs, passwords

Note: Math.random() and ThreadLocalRandom are not secure either. If a value protects an account or data, use SecureRandom.


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 is NativePRNG, which reads from /dev/urandom. On Windows it is usually DRBG.
  • getInstanceStrong() returns the algorithm listed in the securerandom.strongAlgorithms security property. On Linux it reads /dev/random and 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 (null here).
Way to createWhen 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 SecureRandom and reuse it, for example in a private static final field. 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:

  • nextBytes overwrites 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, KeyGenerator is still the cleaner choice, because it returns a proper SecretKey object. Internally it also uses SecureRandom.


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 an IntStream of 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 uses SecureRandom, 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 %06d pads with zeros so 48213 becomes 048213. 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 SecureRandom again 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-seeded SecureRandom adds 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:

  1. Unguessable token. createResetLink fills 32 bytes from a shared SecureRandom and encodes them as a 43-character URL-safe string.
  2. 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.
  3. Single use. redeem removes the record as soon as it is found, so the second attempt fails.
  4. Expiry. Each record keeps an expiresAt time 15 minutes after creation. Passing now as a parameter makes the expiry easy to demonstrate and to test.
  5. Constant-time check. MessageDigest.isEqual compares the hashes without stopping at the first different byte, so response timing reveals nothing about the stored value.
  6. 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.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java SecureRandom and get answers drawn from it.

Signed-in readers only.