Generating random Strings using Streams

suggest change

It is sometimes useful to create random Strings, maybe as Session-ID for a web-service or an initial password after registration for an application. This can be easily achieved using Streams.

First we need to initialize a random number generator. To enhance security for the generated Strings, it is a good idea to use SecureRandom.

Note: Creating a SecureRandom is quite expensive, so create it once and reuse it. It gathers entropy itself. setSeed supplements the current seed rather than replacing it; calling it with a guessable value is not a reseed step.

private static final SecureRandom rng = new SecureRandom(SecureRandom.generateSeed(20));
// 20 seed bytes matches the length used in the SecureRandom JavaDoc examples.
// generateSeed and this constructor may block while entropy is gathered.

When creating random Strings, we usually want them to use only certain characters (e.g. only letters and digits). Therefore we can create a method returning a boolean which can later be used to filter the Stream.

// true for 0-9, A-Z, and a-z
boolean useThisCharacter(char c) {
    // Limit the range so letters outside this block (for example CJK) are excluded.
    return c >= '0' && c <= 'z' && Character.isLetterOrDigit(c);
}

Next, use the RNG to build a random string of the requested length from characters that pass useThisCharacter.

public String generateRandomString(long length) {
    // There is no CharStream. IntStream.ints(origin, bound) is origin-inclusive and bound-exclusive.
    // Stay inside the char range: a code point above Character.MAX_VALUE does not fit in a char.
    // filter(c -> this::useThisCharacter) does not compile: that lambda returns a method reference.
    Stream<Character> randomCharStream = rng.ints('0', 'z' + 1)
        .mapToObj(i -> (char) i)
        .filter(this::useThisCharacter)
        .limit(length);

    String randomString = randomCharStream.collect(StringBuilder::new, StringBuilder::append, StringBuilder::append).toString();
    return randomString;
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents