Aventinus
Aventinus

Reputation: 1382

How to create a random output of a certain bit size in Java?

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

Answers (3)

rossum
rossum

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

MrPublic
MrPublic

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

reineckm
reineckm

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

Related Questions