Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I found a great solution by simply mimicking what Java's SecureRandom.nextInt(int) is doing at here: <a href="http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/security/SecureRandom.java#SecureRandom.next%28int%29" rel="nofollow">SecureRandom.nextInt(int)</a> Will post code as soon as I can get to code it (I'm busy at the moment). I plan to use the code I develop from it, since I confirmed the proposed solution has a bias (it is not acceptable at all).</p> <p>Here is the adaptation of the JDK code. Notice the limitations on 31 bit numbers, since I realized JS does all its bitwise operations on two's complement with 32 bits. I did not implement the special case for power of 2 numbers since I won't be using it. The solution is for numbers in general and not only powers of 10... I'm sure there must be a better solution for numbers with base 10, but whatever. I rewrote the code to not use my libraries and to make it in English, so that others can use it more easily.</p> <pre><code>var crypto_random_number_range = function (n, cb) { //result is a number from 0 a n-1 //Javascript works with 32 bits for bitwise operations but these are signed (2-complement), so it is good to limit the size of n if (n &lt;= 0 || n &gt; 2147483647) { return cb("n must be larger than 0 and smaller than 2147483647", null); } var bits, val; async.doWhilst( function (cb2) { crypto.randomBytes(4, function (err, rbytes) { if (err) { return cb2(err); } bits = ((rbytes[3] &amp; 0x7f) &lt;&lt; 24) + (rbytes[2] &lt;&lt; 16) + (rbytes[1] &lt;&lt; 8) + rbytes[0]; val = bits % n; cb2(); }); }, function () { return (bits - val + (n-1)) &lt; 0; }, function (err) { if (err) { return cb(err, null); } return cb(null, val); } ); } </code></pre> <p>Did several tests, it seems to be working just fine.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload