Generate a random string with a specific bit size in java

java

Solution

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

Problem

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

Original source