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.
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.
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:
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:
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.
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.Randomfor tokens that need to be unpredictable. - Recreating
SecureRandomevery 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 normalSecureRandomis already appropriate.
Summary
- Use
SecureRandomfor 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
SecureRandominstance rather than recreating it. - Treat token length as part of the security design, not just formatting.
Related reading
- How to generate buildConfigField with String type
- How to generate OpenAPI 3.0 YAML file from existing Spring REST API?
- How to generate serial version UID in Intellij
- How to generate Swagger UI from javadocs?
- How to generate TimeUUID in Java/Scala
- How to generate UML diagrams (especially sequence diagrams) from Java code?
- How to get a path to a resource in a Java JAR file
- How to get a reversed list view on a list in Java?

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseTrack 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.