Explain Codes LogoExplain Codes Logo

How to generate a random alpha-numeric string

java
random-string-generation
security
performance
Anton ShumikhinbyAnton Shumikhin·Aug 22, 2024
TLDR

Generate a random alpha-numeric string in Java using the SecureRandom class and a StringBuilder for efficiency:

import java.security.SecureRandom; public class RandomStringGenerator { public static String generateRandomAlphaNumeric(int length) { String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; // The world of alpha-numeric characters! SecureRandom random = new SecureRandom(); StringBuilder randomString = new StringBuilder(length); for (int i = 0; i < length; i++) { randomString.append(characters.charAt(random.nextInt(characters.length()))); // And... the lucky character is... } return randomString.toString(); // Ta-da! Here's your random string! } public static void main(String[] args) { System.out.println(generateRandomAlphaNumeric(10)); // Example: "B5T2k1L3pO" - Looks like my cat walked on the keyboard! } }

Just call generateRandomAlphaNumeric with the desired string length as a parameter.

Deep dive: what you need to know about random string generation

Entropy and performance

Optimal performance can be achieved by reusing an instance of SecureRandom, enabling a satisfying randomness and great efficiency. For creating hard-to-predict unique IDs, the high entropy of SecureRandom is your go-to.

Length matters

Balancing between uniqueness and resource usage is crucial. A length of 12 characters is often a good start for uniqueness over 500,000 generations, but adjust as needed. Use Apache Commons Lang's RandomStringGenerator and its handy .generate(length) method for dynamic length selection.

Character sets and pre-baked solutions

You can define character sets with Apache Commons Lang's CharacterPredicates.LETTERS and DIGITS, or set custom ranges. Choose according to your needs. Beware: RandomStringUtils is deprecated as of version 3.6.

UUIDs: handle with care

UUIDs can be tempting as a one-line solution, but remember they can be quite predictable and inefficient for certain cases such as session IDs. Mixing SecureRandom and a character set is often a better approach.

Mastering the unexpected: dealing with the "birthday paradox"

Collisions: not as rare as you might think

Even in random sequences, collisions can occur more often than intuition suggests. That's the "birthday paradox", and it's crucial to understand it to gauge the security of your random string generation.

The UUID temptation and predictability

Although UUID.randomUUID() provides a quick unique string, it's not always the best option due to its predictability. To increase randomness, character filtering and entropy control techniques can be used.

Practical applications

Understanding this helps you to generate session tokens, one-time passwords, or user-friendly IDs with the right balance between security and efficiency.