Search code examples
javarandombitsecure-random

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.


Solution

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