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
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);
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.
If you're interested in a random unique 128 bit string, I'd recommend UUID.randomUUID()
Alternatives would include ...
- http://jug.safehaus.org/
- http://johannburkard.de/software/uuid/
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.)
精彩评论