Note that there are some explanatory texts on larger screens.

plurals
  1. POGenerating cryptographc random number for modulus of powers of 10 with node.js
    text
    copied!<p>Using the crypto library I can require the library to give me a number of random bytes. The thing is that this bytes are numbers from 0 to 255 each (inclusive) and thus it is not that simple to create a uniformly distributed results.</p> <p>What I mean is the following:</p> <p>The function receives a number N, which is 10, 100, ... 10^b, where b is a number between 1 and 8 (could be bigger, but I don't need anything larger) and returns a number between 0 and the given number (not inclusive to the given number), so say if N is 100, the results of the function are from 0 to 99, and if N is 10 the results are from 0 to 9. </p> <p>You can create a random number by using Math.random and just multiplying by N and then using floor. However, Math.random is not cryptographically safe, so it must be done by using randomly generated number that are of 2^8m, where m is just whatever number of bytes is given to crypto.randomBytes.</p> <p>I created a simple function which is working, apparently. However, I am aware that it is fairly easy to induce some bias into random numbers and I would just like to have it validated, since it is somewhat important for the project.</p> <pre><code>genera_aleatorio_residuo_potencia10 : function (n, cb) { var digitos = Math.log(n) / Math.LN10; var extra_base2 = digitos &gt; 8 ? digitos - 8 : 0; if (Math.floor(digitos + .4) - digitos &gt; 0.00000001) { return cb("Numero no es potencia de 10 (10, 100, 1000...)", null); } digitos = Math.round(digitos); async.parallel({ r1 : crypto_helper.generador_random_bytes(1), r2 : crypto_helper.generador_random_bytes(1) }, function (err, res) { if (err) { return cb(err, null); } var r1 = res.r1[0] + 1; var r2 = res.r2[0] + 1; var aleatorio = (Math.pow(5, digitos) - 1) * Math.pow(2, extra_base2) * r1 + r2; cb(null, aleatorio % n); }); } </code></pre> <p>Needless to say: crypto_helper.generador_random_bytes is a wrapper of node.js' crypto.randomBytes that I frequently use to make it friendlier with the async library.</p> <p>My reasoning for using Math.pow(5, digitos) and the Math.pow(2, extra_base2) is for the least common multiple between N and 256. In practice, n will never be larger than 100000000, so the Math.pow(2, extra_base2) shouldn't be used in our product, but I would still like to be sure it makes sense to other people.</p>
 

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