Description
Using % to map uniform random values to a smaller range makes some results more frequent when the number of inputs is not divisible by the number of outputs. This bias can occur even with cryptographically secure random bytes.
Potential impact
Some authentication codes, invitations or tokens may be easier to guess or more likely to repeat, even when every possible value can still occur.
Remediation
- In Node.js, use
crypto.randomInt()for a number in a range. If implementing the conversion yourself, use rejection sampling. Keep only the range in which each output has the same number of inputs and draw again for values outside it. - For string tokens, encode enough random bytes as hex or base64url, or use a reviewed library such as
crypto-random-string.
Examples
Before
javascript
// Unsafe: generate a six-digit code with modulo bias
const crypto = require("crypto");
function generateOtpBad() {
// Using % to reduce the range to 0..999999 introduces bias
const raw = crypto.randomBytes(4).readUInt32BE();
const n = raw % 1_000_000; // Unsafe: not uniform
return n.toString().padStart(6, "0");
}
console.log(generateOtpBad());
After
javascript
// Use an unbiased API or rejection sampling
const crypto = require("crypto");
// 1) Recommended: the built-in unbiased Node.js API
function generateOtpSafe() {
const n = crypto.randomInt(0, 1_000_000); // Exclusive upper bound, uniform distribution
return n.toString().padStart(6, "0");
}
// 2) Alternative: rejection sampling
function generateOtpSafeLegacy() {
const bound = 1_000_000;
const max = Math.floor(0x1_0000_0000 / bound) * bound; // Largest multiple of bound no greater than 2^32
while (true) {
const r = crypto.randomBytes(4).readUInt32BE();
if (r < max) {
return (r % bound).toString().padStart(6, "0");
}
}
}
console.log(generateOtpSafe());
crypto.randomInt(0, 1_000_000) selects uniformly from 0 through 999999. The alternative discards values at or above max before taking the remainder, producing the same distribution.