Reputation: 1382
I want to create a random alpha-numeric string whose bit count will always be of size k. The size k will be something relatively big (varying from 128 to 2048 or more). I'm reading this excellent thread and I'm trying to figure something out using the Random
and the SecureRandom
class but to no avail.
To be more precise, the result doesn't have to be necessarily a string, it could be anything as long as it is random and its bit count is always k.
Upvotes: 1
Views: 765
Reputation: 15693
Another possibility is the BigInteger
constructor: BigInteger(int numBits, Random rnd)
.
Depending on how secure you need your random bits to be, use either Random
or SecureRandom
for the second parameter. There are various ways to convert a BigInteger
to whatever final format you want. To get a string, use BigInteger.toString(2)
where the 2 is the radix for binary.
Upvotes: 1
Reputation: 518
If you truly want a specific number of bits, and cannot settle for the multiples of 8 that bytes can do, try using booleans with SecureRandom
SecureRandom sr = new SecureRandom();
boolean bools[] = new boolean[k];
for(int x = 0; x < bools.length; x++){
bools[x] = sr.nextBoolean();
}
Upvotes: 0
Reputation: 56
Have you checked http://docs.oracle.com/javase/7/docs/api/java/security/SecureRandom.html?
If you need 128 bit of random Data you would need 16 bytes in Java (because a byte is 8 bit) so after (shamelessly copied from said API):
SecureRandom random = new SecureRandom();
byte bytes[] = new byte[16];
random.nextBytes(bytes);
now you have a Array with 128 bit of random Data. For 2048 it's a byte[256];
Upvotes: 3