问题
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?
回答1:
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;
}
回答2:
bytes.toString(); is wrong, try using Arrays.toString(bytes) - or new String(bytes) if you want to convert it to a String.
来源:https://stackoverflow.com/questions/46261055/how-to-generate-a-securerandom-string-of-length-n-in-java