Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a SecureRandom string of length n in Java? [duplicate]

Tags:

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?

like image 473
kovac Avatar asked Sep 17 '17 05:09

kovac


People also ask

How do you generate a random string of characters in Java?

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.

How do you generate a secure random string?

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.

What is SecureRandom in Java?

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.


1 Answers

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; } 
like image 69
kovac Avatar answered Sep 17 '22 19:09

kovac