How do you generate a secure random (or pseudo-random) alphanumeric string in Java efficiently?
SecureRandom randomGenerator = new SecureRandom(); byte[] randomBytes = new byte[20]; randomGenerator. nextBytes(randomBytes); String randomString = new BigInteger(1, randomBytes). toString(16); It you want to a little more efficient variant, specify randomGenerator as class field or as a static field.
Generating a Secure Random String$random = random_bytes(10); The function returns a random string, suitable for cryptographic use, of the number bytes passed as an argument (10 in the above example). The random_bytes() function returns a binary string which may contain the \0 character.
Using randomUUID() java. util. UUID is another Java class that can be used to generate a random string. It offers a static randomUUID() method that returns a random alphanumeric string of 32 characters.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With