Java
Secure Coding
Random String Generation
Alphanumeric
Efficiency

How to generate a secure random alphanumeric string in Java efficiently?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

When a random string will be used for tokens, invite codes, password resets, or session identifiers, the generator must be unpredictable. In Java that means starting with SecureRandom, then choosing characters from a fixed alphanumeric alphabet with as little extra allocation as possible.

The efficient part is not about exotic algorithms. It is about avoiding poor randomness sources, avoiding needless conversions, and generating the exact number of characters you need in one pass.

Use SecureRandom and a Fixed Alphabet

The usual approach is to define the allowed characters once, then fill a character buffer with random indexes into that alphabet.

java
1import java.security.SecureRandom;
2
3public final class TokenGenerator {
4    private static final char[] ALPHANUMERIC =
5        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
6            .toCharArray();
7
8    private static final SecureRandom RANDOM = new SecureRandom();
9
10    private TokenGenerator() {
11    }
12
13    public static String generate(int length) {
14        if (length <= 0) {
15            throw new IllegalArgumentException("length must be greater than 0");
16        }
17
18        char[] buffer = new char[length];
19        for (int i = 0; i < length; i++) {
20            int index = RANDOM.nextInt(ALPHANUMERIC.length);
21            buffer[i] = ALPHANUMERIC[index];
22        }
23        return new String(buffer);
24    }
25
26    public static void main(String[] args) {
27        System.out.println(generate(24));
28    }
29}

This is secure for normal application use because SecureRandom is designed for cryptographic unpredictability. It is also efficient because the alphabet is reused and the output buffer is allocated once.

Why Random Is Not Good Enough

Developers sometimes reach for java.util.Random because it is fast and familiar. That is a mistake for security-sensitive strings. Random is deterministic and can be predicted if an attacker can infer enough internal state.

For non-security tasks such as generating demo data, Random may be fine. For anything that grants access or proves identity, use SecureRandom and accept the small extra cost.

Prefer a char[] Buffer Over Repeated Concatenation

If you already know the target length, a character array is a clean fit. It avoids repeated growth behavior and makes the output construction explicit.

A StringBuilder version also works:

java
1public static String generateWithBuilder(int length) {
2    StringBuilder builder = new StringBuilder(length);
3    for (int i = 0; i < length; i++) {
4        builder.append(ALPHANUMERIC[RANDOM.nextInt(ALPHANUMERIC.length)]);
5    }
6    return builder.toString();
7}

That code is still reasonable. The char[] version is just a little more direct because the final size is known in advance.

Choose the Length Based on the Use Case

Security depends on both the randomness source and the size of the search space. With 62 possible characters, each extra character increases the number of possible tokens significantly.

Practical guidance:

  • short human-entered codes should be longer than you think if they grant access
  • backend-only secrets can usually afford much longer lengths
  • avoid shortening tokens for appearance alone

If the token is not meant to be typed by humans, there is rarely a good reason to make it very short.

Reuse the SecureRandom Instance

Create the generator once and reuse it. Reconstructing SecureRandom on every call adds overhead and does not improve security.

For most applications, a static final instance is the right choice:

java
private static final SecureRandom RANDOM = new SecureRandom();

That keeps the call site cheap and the implementation simple. You usually do not need SecureRandom.getInstanceStrong() for this kind of token generation, and in some environments it may be unnecessarily slow or blocking.

Validate the Output Shape

You cannot unit-test randomness quality in a simple test, but you can test the format contract.

java
1public static void validate() {
2    String token = generate(32);
3    boolean matches = token.matches("[A-Za-z0-9]{32}");
4    System.out.println(matches);
5}

That verifies the method returns the expected length and alphabet. The security guarantee still comes from using the correct randomness primitive, not from the regex test.

Common Pitfalls

  • Using java.util.Random for tokens that need to be unpredictable.
  • Recreating SecureRandom every time a token is generated.
  • Building the string through repeated concatenation instead of a buffer.
  • Choosing a token length based only on aesthetics.
  • Using getInstanceStrong() by default when normal SecureRandom is already appropriate.

Summary

  • Use SecureRandom for any security-sensitive random string in Java.
  • Generate characters from a fixed alphanumeric alphabet.
  • Fill a char[] buffer when you already know the target length.
  • Reuse the SecureRandom instance rather than recreating it.
  • Treat token length as part of the security design, not just formatting.

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.