Random Alphanumeric Generator in Java

The following Java example program generates a cryptographically secure random alphanumeric string. If cryptographic security is not a requirement, the SecureRandom class can be replaced with Random class for a much faster implementation.

The following function can be used to generate random strings with a specified length. It is also possible to specify a subset of character set in the random string by modifying the CHARACTER_SET variable.

import java.security.SecureRandom;

// Example - Random alphanumeric generator in Java
public class RandomAlphaNumericGenerator {
    private static SecureRandom random = new SecureRandom();
    private static final String CHARACTER_SET="0123456789abcdefghijklmnopqrstuvwxyz"; 
    public static void main(String[] args) {
        System.out.println("Random Alphanumeric String:"+getRandomString(32));

    // Create a random alphanumeric string
    private static String getRandomString(int len) {
        StringBuffer buff = new StringBuffer(len);
        for(int i=0;i<len;i++) {
            int offset = random.nextInt(CHARACTER_SET.length());
        return buff.toString();