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;
}
Answer from kovac on Stack OverflowVideos
How many random strings can I generate at once?
Can I use randomly generated strings as passwords?
Can I generate strings using only specific characters?
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;
}
bytes.toString(); is wrong, try using Arrays.toString(bytes) - or new String(bytes) if you want to convert it to a String.
ยป npm install secure-random-string
Initialize an array containing all the accepted chars (CHARS_ARRAY), then instantiate a SecureRandom instance, and call nextInt(CHARS_ARRAY.length) repeatedly to get a random index in your char array. Append each char to a StringBuilder until you get the expected number of chars.
If you use Apache Commons Lang, the easiest way is
RandomStringUtils.random(20, 0, 0, true, true, null, new SecureRandom());