Generate a random string with a specific bit size

2020-02-13 08:00发布

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

标签: java
4条回答
三岁会撩人
2楼-- · 2020-02-13 08:42

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.)

查看更多
何必那么认真
3楼-- · 2020-02-13 08:46

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.

查看更多
Lonely孤独者°
4楼-- · 2020-02-13 08:54

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

Alternatives would include ...

查看更多
ゆ 、 Hurt°
5楼-- · 2020-02-13 09:05

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);
查看更多
登录 后发表回答