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?
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.
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.
public class SecureRandom extends Random. This class provides a cryptographically strong random number generator (RNG). A cryptographically strong random number minimally complies with the statistical random number generator tests specified in FIPS 140-2, Security Requirements for Cryptographic Modules, section 4.9. 1.
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; }
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