diedthreetimes - 2 years ago 155

Android Question

Specifically, I just want to generate a cryptographically secure random number between 0 and some number *x*.

In OpenSSL this is done with the function

`bn_range`

I can implement it myself using Java's

`BigInteger(int bits, Random r)`

Is there a standard way to do this in Java?

P.S. I am actually using Android, but I don't know how to do it in standard Java.

EDIT:

`BigInteger`

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

As far as I can tell, this functionality is not provided. But it is easy enough to implement yourself.

```
Random r = new SecureRandom();
BigInteger q = something_big;
BigInteger ans;
do
ans = BigInteger(bits_in_q, r);
while (ans.compareTo(q) >= 0); // bn_rand_range generates numbers < q
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**