William
William

Reputation: 141

Generate a random string with a specific bit size in java

How do i do that? Can't seems to find a way. Securerandom doesn't seems to allow me to specify bit size anywhere

Upvotes: 13

Views: 31414

Answers (4)

theomega
theomega

Reputation: 32051

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

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

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

For example, use the Apache Commons Codec and do:

Random random = ThreadLocalRandom.current();
byte[] r = new byte[256]; //Means 2048 bit
random.nextBytes(r);
String s = Base64.encodeBase64String(r);

Upvotes: 32

atomic_ice
atomic_ice

Reputation: 83

Similar to the other answer with a minor detail

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

Instead of simply using Base64 encoding, which can leave you with a '+' in the out, make sure it doesn't contain any characters which need to be further URL encoded.

Upvotes: 4

qwerty
qwerty

Reputation: 3869

If you're interested in a random unique 128 bit string, I'd recommend UUID.randomUUID()

Alternatives would include ...

Upvotes: 3

Paŭlo Ebermann
Paŭlo Ebermann

Reputation: 74800

The meaning of "random String" is not clear in Java.

You can generate random bits and bytes, but converting these bytes to a string is normally not simply doable, as there is no build-in conversion which accepts all byte arrays and outputs all strings of a given length.

If you only want random bytes, do what theomega proposed, and ommit the last line.

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

Upvotes: 1

Related Questions