dimanche 19 novembre 2017

Secure random int generation


I've written the following code which generates a random int array of times numbers between 1 and max (inlusive):

'use strict';
const crypto = require('crypto');
const roller = {};

function getByteCount(max, times){
    return Math.ceil(Math.log2(Math.pow(max, times)) / 8);
}

roller.roll = function(max, times){
    const byteCount = getByteCount(max, times);
    const randomToken = crypto.randomBytes(byteCount).readUIntBE(0, byteCount);
    var remainingToken = randomToken;
    const dice = [];
    for(var i = 0; i < times; i++){
        dice.push((remainingToken % max) + 1);
        remainingToken = Math.floor(remainingToken / max);
    }
    return dice;
};

module.exports = roller;

However I read this article which highly suggests not using crypto.randomBytes directly.
This made me curious: I don't think I made the mistake described in the article where using modulo results in some values being more likely.
My application (at least this part) does not really have a need for "true randomness", so my question is basically:
Does the suggested random-number-csprng package have any benefits/drawbacks when looking at performance, memory and unpredictability?




Aucun commentaire:

Enregistrer un commentaire