Generating unique keys using RandomStringUtils of apache commons
Categories:
Generating Unique Keys with Apache Commons RandomStringUtils

Learn how to leverage Apache Commons Lang's RandomStringUtils to generate unique, random keys for various applications in Java, from session IDs to temporary tokens.
In many software development scenarios, there's a need to generate unique, random strings. These strings can serve various purposes, such as session identifiers, temporary passwords, API keys, file names, or unique identifiers for database records. While Java provides basic random number generation, the Apache Commons Lang library offers a more robust and convenient utility called RandomStringUtils
for generating diverse types of random strings.
This article will guide you through the process of using RandomStringUtils
to create unique keys, covering its core functionalities, common use cases, and best practices.
Understanding RandomStringUtils
RandomStringUtils
is part of the Apache Commons Lang library, a collection of utility classes for the Java API. It simplifies the generation of random strings by providing methods to control the length, character set, and other properties of the generated string. This makes it an excellent choice for scenarios where you need more than just a random number.
flowchart TD A[Start] --> B{Need Unique Key?} B -- Yes --> C[Add Apache Commons Lang Dependency] C --> D[Import RandomStringUtils] D --> E{Define Key Requirements?} E -- Length, Charset --> F[Use RandomStringUtils.randomXXX()] F --> G[Generate Unique Key] G --> H[Use Key in Application] H --> I[End] E -- No / Default --> F
Workflow for generating unique keys using RandomStringUtils
Getting Started: Adding the Dependency
Before you can use RandomStringUtils
, you need to include the Apache Commons Lang library in your project. If you're using Maven or Gradle, add the following dependency to your pom.xml
or build.gradle
file, respectively.
Maven
Gradle
implementation 'org.apache.commons:commons-lang3:3.12.0'
Generating Basic Random Strings
The simplest way to generate a random string is by specifying its length. RandomStringUtils
provides several random()
methods that allow you to control the character set used.
import org.apache.commons.lang3.RandomStringUtils;
public class KeyGenerator {
public static void main(String[] args) {
// Generate a random string of 10 characters, including letters and numbers
String randomKey1 = RandomStringUtils.randomAlphanumeric(10);
System.out.println("Alphanumeric Key: " + randomKey1);
// Generate a random string of 15 characters, only letters
String randomKey2 = RandomStringUtils.randomAlphabetic(15);
System.out.println("Alphabetic Key: " + randomKey2);
// Generate a random string of 8 characters, only numbers
String randomKey3 = RandomStringUtils.randomNumeric(8);
System.out.println("Numeric Key: " + randomKey3);
// Generate a random string of 12 characters, including ASCII printable characters
String randomKey4 = RandomStringUtils.randomAscii(12);
System.out.println("ASCII Key: " + randomKey4);
}
}
Examples of basic random string generation
RandomStringUtils
with a timestamp or a UUID to minimize collision probability. While RandomStringUtils
provides randomness, it doesn't guarantee global uniqueness on its own.Generating Strings with Custom Character Sets
Sometimes you need more control over the characters used in your unique key. RandomStringUtils
allows you to specify a custom character set, which is particularly useful for generating keys that adhere to specific security requirements (e.g., including special characters) or excluding ambiguous characters (e.g., 'l', '1', 'I', '0', 'O').
import org.apache.commons.lang3.RandomStringUtils;
public class CustomKeyGenerator {
public static void main(String[] args) {
// Generate a random string of 16 characters using a custom set of letters, numbers, and symbols
String customCharset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()";
String customKey1 = RandomStringUtils.random(16, customCharset);
System.out.println("Custom Key 1: " + customKey1);
// Generate a random string of 20 characters, excluding ambiguous characters
String nonAmbiguousCharset = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789"; // Excludes I, O, 0, 1, l
String customKey2 = RandomStringUtils.random(20, nonAmbiguousCharset);
System.out.println("Custom Key 2 (Non-Ambiguous): " + customKey2);
// Generate a random string using only hexadecimal characters
String hexCharset = "0123456789ABCDEF";
String hexKey = RandomStringUtils.random(32, hexCharset);
System.out.println("Hexadecimal Key: " + hexKey);
}
}
Generating random strings with custom character sets