Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RandomStringGenerator to generate alphanumeric strings

Tags:

java

Can I use Apache's common-text RandomStringGenerator to generate random alphanumeric strings (numbers and lowercase/uppercase letters)?

like image 310
David Riccitelli Avatar asked Jul 06 '17 11:07

David Riccitelli


People also ask

How do you create an alphanumeric key?

To generate a random string of alphanumeric characters (alphanumeric sequence), start by specifying which alphabet to use. "Alphabet" here means simply the collection (or 'bag') of characters from which the random alphanumeric generator has to pick.

How do I randomly generate a string in Excel?

In the Insert Random Data dialog box, click String tab, and choose the type of characters as you need, then specify the length of the string in the String length box, and finally click the OK button. See screenshot: Then the selected range has been filled with random character strings.


3 Answers

RandomStringGenerator generator = new RandomStringGenerator.Builder()
    .selectFrom("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".toCharArray())
    .build();

I kind of prefer this way rather than generating character codes and filtering out ones I don't want. And implicitly assuming that '0'..'z' includes all the codes I want, including capital letters (based on the ascii code chart).

In addition, depending on the application (eg password generation), you might want to use a CSPRNG (secure PRNG) seeded by a true-randomness source:

.usingRandom(new SecureRandom()::nextInt)

The default SecureRandom seed is from a true-randomness source of OS hardware device entropy.

like image 189
Curtis Yallop Avatar answered Oct 13 '22 21:10

Curtis Yallop


Yes, using the following code:

import static org.apache.commons.text.CharacterPredicates.DIGITS;
import static org.apache.commons.text.CharacterPredicates.LETTERS;

// ...

RandomStringGenerator generator = new RandomStringGenerator.Builder()
        .withinRange('0', 'z')
        .filteredBy(LETTERS, DIGITS)
        .build();
like image 39
David Riccitelli Avatar answered Oct 13 '22 22:10

David Riccitelli


I use this:

static char[] chars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'q', 'w', 'e', 'r', 't', 'z', 'u', 'i', 'o', 'p', 'a', 's',
        'd', 'f', 'g', 'h', 'j', 'k', 'l', 'y', 'x', 'c', 'v', 'b', 'n', 'm', 'Q', 'W', 'E', 'R', 'T', 'Z', 'U', 'I', 'O', 'P', 'A',
        'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'Y', 'X', 'C', 'V', 'B', 'N', 'M' };

private static String randomString(int length) {
    StringBuilder stringBuilder = new StringBuilder();

    for (int i = 0; i < length; i++) {
        stringBuilder.append(chars[new Random().nextInt(chars.length)]);
    }
    return stringBuilder.toString();
}

or

private static String randomString(int length) {
    StringBuilder stringBuilder = new StringBuilder();

    for (int i = 0; i < length; i++) {
        switch (new Random().nextInt(3)) {
            case 0:
                stringBuilder.append((char) (new Random().nextInt(9) + 48));
                break;
            case 1:
                stringBuilder.append((char) (new Random().nextInt(25) + 65));
                break;
            case 2:
                stringBuilder.append((char) (new Random().nextInt(25) + 97));
                break;
            default:
                break;
        }
    }
    return stringBuilder.toString();
}
like image 22
mate0406 Avatar answered Oct 13 '22 21:10

mate0406