How to generate a random string
Short answer
Pick random characters from an alphabet string. For passwords and tokens use SecureRandom — its output cannot be predicted:
static final String ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
static final SecureRandom RANDOM = new SecureRandom();
String randomString(int length) {
var result = new StringBuilder(length);
for (int i = 0; i < length; i++) {
result.append(ALPHABET.charAt(RANDOM.nextInt(ALPHABET.length())));
}
return result.toString();
}
void main() {
IO.println(randomString(12));
}Output:
G0fHdMG1t29TThe result is different every time.
A token from bytes
For long tokens it is easier to take random bytes and encode them with URL-safe Base64:
void main() {
byte[] bytes = new byte[24];
new SecureRandom().nextBytes(bytes);
IO.println(Base64.getUrlEncoder().withoutPadding().encodeToString(bytes));
}Output:
odBXRC78P41xba6fnFUZf53ovW79tmulA unique identifier
If you just need a unique ID, use UUID:
void main() {
IO.println(UUID.randomUUID());
}Output:
26d2e800-7d9e-48cd-b6bf-6645d141f886A repeatable result
Tests sometimes need the same "random" string. Random with a fixed seed produces the same sequence every time:
void main() {
var random = new Random(42);
var result = new StringBuilder();
for (int i = 0; i < 6; i++) {
result.append((char) ('a' + random.nextInt(26)));
}
IO.println(result);
}Output:
ahwmarCommon mistake
Generating passwords and tokens with Random or Math.random(). Their sequence can be reconstructed from a few values. Anything security-related needs SecureRandom.
Functions used in this recipe
- Random — A random number generator: integers in a range, decimals, booleans.
- StringBuilder.append() — Adds a value to the end of a StringBuilder.