How to generate a SecureRandom string of length n in Java?

kovac picture kovac · Sep 17, 2017 · Viewed 17.6k times · Source

I'm generating a random string using:

private String generateSafeToken() {
    SecureRandom random = new SecureRandom();
    byte bytes[] = new byte[512];
    random.nextBytes(bytes);
    return bytes.toString();
}

This gives a string of length 11 such as [B@70ffc557. How can I make this above method return a string of a specified length. For example 20 characters?

Answer

kovac picture kovac · May 17, 2018

I don't understand why this is marked duplicate when clearly the "duplicate" question referred here doesn't ask the same question - though an answer down below contains this information. In any case, the answer I was looking for is below, incase if it helps anyone else.

private String generateSafeToken() {
    SecureRandom random = new SecureRandom();
    byte bytes[] = new byte[20];
    random.nextBytes(bytes);
    Encoder encoder = Base64.getUrlEncoder().withoutPadding();
    String token = encoder.encodeToString(bytes);
    return token;
}