A random sequence of strings will always have a possibility of repeating, otherwise it's not really random. RandomStringUtils is not really random, but it's trying to be as close to random as it can be, which seems contrary to your goal. If you must use randomly generated keys, then you should at least use java.util.UUID.randomUUID because that is made to be used that way.

You may find this link interesting: Generating unique IDs

Answer from Geo on Stack Overflow
🌐
Apache Commons
commons.apache.org › proper › commons-lang › javadocs › api-3.9 › org › apache › commons › lang3 › RandomStringUtils.html
RandomStringUtils (Apache Commons Lang 3.9 API)
Please note that the Apache Commons project provides a component dedicated to pseudo-random number generation, namely Commons RNG, that may be a better choice for applications with more stringent requirements (performance and/or correctness). ... RandomStringUtils instances should NOT be constructed in standard programming. Instead, the class should be used as RandomStringUtils.random(5);. This constructor is public to permit tools that require a JavaBean instance to operate.
🌐
Baeldung
baeldung.com › home › java › java string › java – generate random string
Java - Generate Random String | Baeldung
May 11, 2024 - @Test public void givenUsingApache_whenGeneratingRandomAlphanumericString_thenCorrect() { String generatedString = RandomStringUtils.randomAlphanumeric(10); System.out.println(generatedString); } And there we have it, creating bounded and unbounded strings with either plain Java, a Java 8 variant, or the Apache Commons Library. Through different implementation methods, we were able to generate bound and unbound strings using plain Java, a Java 8 variant, or the Apache Commons Library. In these Java examples, we used java.util.Random, but one point worth mentioning is that it is not cryptographically secure.
🌐
Educative
educative.io › answers › what-is-randomstringutilsrandomalphabetic-in-java
What is RandomStringUtils.randomAlphabetic() in Java?
the methods in Java that can be called without creating an object of the class. method of the RandomStringUtils class which is used to generate random strings consisting of alphabetic characters.
🌐
GitHub
github.com › apache › commons-lang › blob › master › src › main › java › org › apache › commons › lang3 › RandomStringUtils.java
commons-lang/src/main/java/org/apache/commons/lang3/RandomStringUtils.java at master · apache/commons-lang
import java.util.function.Supplier; · /** * Generates random {@link String}s. * <p> * Use {@link #secure()} to get the singleton instance based on {@link SecureRandom#SecureRandom()} which uses a secure random number generator implementing the · * default random number algorithm.
Author   apache
🌐
Apache Commons
commons.apache.org › proper › commons-lang › jacoco › org.apache.commons.lang3 › RandomStringUtils.java.html
RandomStringUtils.java - Apache Commons
* </p> * * @deprecated TODO Make private in 4.0. */ @Deprecated public RandomStringUtils() { this(SECURE_SUPPLIER); } private RandomStringUtils(final Supplier<RandomUtils> random) { this.random = random; } /** * Creates a random string whose length is the number of characters specified.
🌐
Educative
educative.io › answers › what-is-randomstringutilsrandomnumeric-in-java
What is RandomStringUtils.randomNumeric() in Java?
describes the methods in Java that can be called without creating an object of the class method of the RandomStringUtils class which is used to generate random string consisting of numeric characters.
Find elsewhere
🌐
Educative
educative.io › answers › what-is-randomstringutilsrandomalphanumeric-in-java
What is RandomStringUtils.randomAlphanumeric() in Java?
the methods in Java that can be called without creating an object of the class. method of the RandomStringUtils class that is used to generate random strings consisting of alphanumeric characters.
🌐
Tabnine
tabnine.com › home page › code › java › org.apache.commons.lang.randomstringutils
org.apache.commons.lang.RandomStringUtils.random java code examples | Tabnine
/** * <p>Creates a random string whose length is the number of characters * specified.</p> * * <p>Characters will be chosen from the set of all characters.</p> * * @param count the length of random string to create * @return the random string ...
🌐
GitHub
github.com › apache › commons-lang › blob › master › src › test › java › org › apache › commons › lang3 › RandomStringUtilsTest.java
commons-lang/src/test/java/org/apache/commons/lang3/RandomStringUtilsTest.java at master · apache/commons-lang
July 31, 2020 - return Stream.of(RandomStringUtils.secure(), RandomStringUtils.secureStrong(), RandomStringUtils.insecure()); ... * Test for LANG-1286. Creates situation where old code would overflow a char and result in a code point outside the specified range. ... final String result = RandomStringUtils.random(2, start, end, false, false, null, fixedRandom);
Author   apache
🌐
Kodejava
kodejava.org › how-do-i-generate-a-random-alpha-numeric-string
How do I generate a random alphanumeric string? - Learn Java by Examples
June 3, 2024 - The code below show you how to use the Apache Commons-Lang RandomStringUtils class to generate some random string data. package org.kodejava.commons.lang; import org.apache.commons.lang3.RandomStringUtils; public class RandomStringUtilsDemo { public static void main(String[] args) { // Creates a 64-chars length random string of number.
🌐
Apache Commons
commons.apache.org › proper › commons-lang › apidocs › src-html › org › apache › commons › lang3 › RandomStringUtils.html
Random - Source code - The Apache Software Foundation
May 4, 2019 - 666 * </p> 667 * 668 * @deprecated ... Supplier<RandomUtils> random) { 676 this.random = random; 677 } 678 679 /** 680 * Creates a random string whose length is the number of characters specified....
🌐
Vultr Docs
docs.vultr.com › java › examples › create-random-strings
Java Program to Create random strings | Vultr Docs
November 25, 2024 - Utilize the RandomStringUtils class which provides methods to create randomized strings.
🌐
Javadevcentral
javadevcentral.com › apache commons lang randomstringutils
Apache Commons Lang RandomStringUtils | Java Developer Central
November 8, 2021 - We will learn about the Apache Commons Lang RandomStringUtils class for generating random strings for simple use cases in this post.
🌐
CodeJava
codejava.net › coding › generate-random-strings-examples
Generate Random Strings in Java Examples
January 13, 2023 - Random String #1: !`;u!k=|Vc Random String #2: %%xB\B25ryhg|zS Random String #3: K/IzJ'}e@z$Vo%`'.Il)You can use this code example to generate random strong passwords. You can use the java.util.UUID class to generate random strings that are kind of Universally Unique Identifier (UUID).
🌐
Apache Commons
commons.apache.org › proper › commons-lang › javadocs › api-3.8 › org › apache › commons › lang3 › RandomStringUtils.html
RandomStringUtils (Apache Commons Lang 3.8 API)
This method has exactly the same semantics as random(int,int,int,boolean,boolean,char[],Random), but instead of using an externally supplied source of randomness, it uses the internal static Random instance. ... ArrayIndexOutOfBoundsException - if there are not (end - start) + 1 characters in the set array. public static String random(int count, int start, int end, boolean letters, boolean numbers, char[] chars, Random random)
🌐
Programiz
programiz.com › java-programming › examples › generate-random-string
Java Program to Create random strings
October 11, 2023 - import java.util.Random; class Main { public static void main(String[] args) { // create a string of all characters String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // create random string builder StringBuilder sb = new StringBuilder(); // create an object of Random class Random random = new Random(); // specify length of random string int length = 7; for(int i = 0; i < length; i++) { // generate random index number int index = random.nextInt(alphabet.length()); // get character specified by index // from the string char randomChar = alphabet.charAt(index); // append the character to string builder sb.append(randomChar); } String randomString = sb.toString(); System.out.println("Random String is: " + randomString); } }
Top answer
1 of 16
1642

Algorithm

To generate a random string, concatenate characters drawn randomly from the set of acceptable symbols until the string reaches the desired length.

Implementation

Here's some fairly simple and very flexible code for generating random identifiers. Read the information that follows for important application notes.

public class RandomString {

    /**
     * Generate a random string.
     */
    public String nextString() {
        for (int idx = 0; idx < buf.length; ++idx)
            buf[idx] = symbols[random.nextInt(symbols.length)];
        return new String(buf);
    }

    public static final String upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    public static final String lower = upper.toLowerCase(Locale.ROOT);

    public static final String digits = "0123456789";

    public static final String alphanum = upper + lower + digits;

    private final Random random;

    private final char[] symbols;

    private final char[] buf;

    public RandomString(int length, Random random, String symbols) {
        if (length < 1) throw new IllegalArgumentException();
        if (symbols.length() < 2) throw new IllegalArgumentException();
        this.random = Objects.requireNonNull(random);
        this.symbols = symbols.toCharArray();
        this.buf = new char[length];
    }

    /**
     * Create an alphanumeric string generator.
     */
    public RandomString(int length, Random random) {
        this(length, random, alphanum);
    }

    /**
     * Create an alphanumeric strings from a secure generator.
     */
    public RandomString(int length) {
        this(length, new SecureRandom());
    }

    /**
     * Create session identifiers.
     */
    public RandomString() {
        this(21);
    }

}

Usage examples

Create an insecure generator for 8-character identifiers:

RandomString gen = new RandomString(8, ThreadLocalRandom.current());

Create a secure generator for session identifiers:

RandomString session = new RandomString();

Create a generator with easy-to-read codes for printing. The strings are longer than full alphanumeric strings to compensate for using fewer symbols:

String easy = RandomString.digits + "ACEFGHJKLMNPQRUVWXYabcdefhijkprstuvwx";
RandomString tickets = new RandomString(23, new SecureRandom(), easy);

Use as session identifiers

Generating session identifiers that are likely to be unique is not good enough, or you could just use a simple counter. Attackers hijack sessions when predictable identifiers are used.

There is tension between length and security. Shorter identifiers are easier to guess, because there are fewer possibilities. But longer identifiers consume more storage and bandwidth. A larger set of symbols helps, but might cause encoding problems if identifiers are included in URLs or re-entered by hand.

The underlying source of randomness, or entropy, for session identifiers should come from a random number generator designed for cryptography. However, initializing these generators can sometimes be computationally expensive or slow, so effort should be made to re-use them when possible.

Use as object identifiers

Not every application requires security. Random assignment can be an efficient way for multiple entities to generate identifiers in a shared space without any coordination or partitioning. Coordination can be slow, especially in a clustered or distributed environment, and splitting up a space causes problems when entities end up with shares that are too small or too big.

Identifiers generated without taking measures to make them unpredictable should be protected by other means if an attacker might be able to view and manipulate them, as happens in most web applications. There should be a separate authorization system that protects objects whose identifier can be guessed by an attacker without access permission.

Care must be also be taken to use identifiers that are long enough to make collisions unlikely given the anticipated total number of identifiers. This is referred to as "the birthday paradox." The probability of a collision, p, is approximately n2/(2qx), where n is the number of identifiers actually generated, q is the number of distinct symbols in the alphabet, and x is the length of the identifiers. This should be a very small number, like 2‑50 or less.

Working this out shows that the chance of collision among 500k 15-character identifiers is about 2‑52, which is probably less likely than undetected errors from cosmic rays, etc.

Comparison with UUIDs

According to their specification, UUIDs are not designed to be unpredictable, and should not be used as session identifiers.

UUIDs in their standard format take a lot of space: 36 characters for only 122 bits of entropy. (Not all bits of a "random" UUID are selected randomly.) A randomly chosen alphanumeric string packs more entropy in just 21 characters.

UUIDs are not flexible; they have a standardized structure and layout. This is their chief virtue as well as their main weakness. When collaborating with an outside party, the standardization offered by UUIDs may be helpful. For purely internal use, they can be inefficient.

2 of 16
903

Java supplies a way of doing this directly. If you don't want the dashes, they are easy to strip out. Just use uuid.replace("-", "")

import java.util.UUID;

public class randomStringGenerator {
    public static void main(String[] args) {
        System.out.println(generateString());
    }

    public static String generateString() {
        String uuid = UUID.randomUUID().toString();
        return "uuid = " + uuid;
    }
}

Output

uuid = 2d7428a6-b58c-4008-8575-f05549f16316