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.
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());
Videos
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.
Why not use Base64 encoding to convert the salt? Look for Apache Commons Codec, Base64 class.
You can then convert the byte array to a String using
Base64.encodeBase64String( salt );
You can turn the bytes in a BigInteger and do a base 62 (=10+26+26) conversion on it.
// Digits listed, so maybe look-alike chars (zero and oh) can be handled.
private static final String digits = "0123...ABC...abc...z";
String humanReadable(byte[] bytes) {
// Ensure that we have a byte array which is a positive big-endian.
if (bytes.length != 0 && bytes[0] < 0) {
byte[] ubytes = new byte[bytes.length + 1];
System.arraycopy(bytes, 0, ubytes, 1, bytes.length);
bytes = ubytes;
}
BigInteger n = new BigInteger(bytes);
StringBuilder sb = new StringBuilder(48);
final BigInteger DIGIT_COUNT = BigInteger.valueOf(digits.length());
while (n.signum() != 0) {
int index = n.mod(DIGITS).intValue();
sb.append(digits.charAt(index));
n = n.div(DIGITS);
}
return sb.toString();
}