I have come up with a function to generate a “cryptographically random” integer within a specific range (minDigits, maxDigits). It keeps generating until one fits the range defined. I would just like to know from someone who may have more knowledge if this is indeed viable.
In the example below I used range of minimum 6 and maximum 6 for a hopefully truly random 6 digit integer leveraging the Javascript Web Crypto API crypto.getRandomValues() method.
More specifically, is this substantially more random than just using Math.random()?
function secureRandomByDigits(minDigits, maxDigits) {
if (minDigits <= 0 || maxDigits <= 0 || minDigits > maxDigits) {
throw new Error('Invalid digit range');
}
const min = Math.pow(10, minDigits - 1);
const max = Math.pow(10, maxDigits) - 1;
// Generate a cryptographically secure random number until it fits the range
let randomInt;
do {
const buffer = new Uint32Array(1);
window.crypto.getRandomValues(buffer);
const fraction = buffer[0] / 0xFFFFFFFF;
randomInt = Math.floor(fraction * (max - min + 1) + min);
} while (randomInt < min || randomInt > max);
return randomInt;
}
// Example usage:
const randomInt = secureRandomByDigits(6, 6);
console.log("Random Integer:", randomInt);