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

kovac :

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?

kovac :

I don't understand why this is marked duplicate when clearly the "duplicate" question referred here doesn't answer the question. 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;
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=431845&siteId=1