Create a random string with a specific bit size in java

How can I do it? Seems unable to find a way. Securerandom doesn't seem to allow me to specify bit size anywhere

+8
java
source share
4 answers

If your bit count can be divided by 8, in other words, you need a full byte count, you can use

byte[] r = new byte[256]; //Means 2048 bit Random.nextBytes(r); String s = new String(r) 

If you don't like strange characters, encode the byte array as base64:

For example, use the Apache Commons Codec and do:

 byte[] r = new byte[256]; //Means 2048 bit Random.nextBytes(r); String s = Base64.encodeBase64String(r); 
+19
source share

The meaning of the "random string" is not clear in Java.

You can generate random bits and bytes, but converting these bytes to a string is usually not easy, as there is no built-in conversion that takes all arrays of bytes and prints all strings of a given length.

If you need only random bytes, do what theomega suggested and omit the last line.

If you need a random string of some character set, it depends on the set. Base64 is an example of such a set, using 64 different ASCII characters to represent 6 bits each (so 4 of these characters represent 24 bits, which will be 3 bytes).

+1
source share

If you are interested in a random unique 128-bit string, I would recommend UUID.randomUUID ()

Alternatives will include ...

+1
source share

Like another answer with minor detail

 Random random = ThreadLocalRandom.current(); byte[] randomBytes = new byte[32]; random.nextBytes(randomBytes); String encoded = Base64.getUrlEncoder().encodeToString(randomBytes) 

Instead of just using Base64 encoding, which can leave you with a “+” character, make sure that it does not contain characters that should be encoded in the future.

+1
source share

All Articles