Scala notes

How to generate random alphanumeric strings


Here is a small code for generating random alphanumeric strings of specified length:

import java.math.BigInteger;

public class KeyGenerator {

private static final SecureRandom secureRandom = new SecureRandom();

public static String generate(int stringLength) {
return new BigInteger(stringLength * 5, secureRandom).toString(32);

This works by choosing a multiple of 5 bits from a cryptographically secure random bit generator and encoding them in base-32.

Each digit in a base-32 number can encode 5 bits. So the multiplier would give the number of resulting characters.

This encoding is compact and efficient, with 5 random bits per character. Compare this to a random UUID, which only has 3.4 bits per character in standard layout, and only 122 random bits in total.

Note that SecureRandom objects are expensive to initialize so you'll want to keep one around and reuse it.

Based on this answer.