I am trying to shuffle an array using a cryptographically secure source of entropy.
I found a similar question, regarding shuffling arrays here How to randomize (shuffle) a JavaScript array?. However almost all solutions make use of Math.random
, which is not secure.
Unfortunately I do not have the reputation to comment/post on that question.
Here is the solution I came up with, which uses Durstenfeld shuffling paired with a CSPRNG for generating random integers in a given range (provided by random-number-csprng lib).
const randomNumber = require("random-number-csprng");
async function secureShuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = await randomNumber(0, i);
const temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
Is this implementation correct and unbiased?
notes:
- for my purposes the array would contain at most ~100 elements
- running nodejs v6.10.3 LTS (transpiled)