Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
crypto: fix randomInt bias
Co-authored-by: Andrey Pechkurov <apechkurov@gmail.com>
  • Loading branch information
tniessen and puzpuzpuz committed Jan 12, 2021
commit b0d845f8aca42d8720e90c9fc29294c89790ac53
19 changes: 9 additions & 10 deletions lib/internal/crypto/random.js
Original file line number Diff line number Diff line change
Expand Up @@ -218,30 +218,29 @@ function randomInt(min, max, callback) {
`<= ${RAND_MAX}`, range);
}

const excess = RAND_MAX % range;
const randLimit = RAND_MAX - excess;
// For (x % range) to produce an unbiased value greater than or equal to 0 and
// less than range, x must be drawn randomly from the set of integers greater
// than or equal to 0 and less than randLimit.
const randLimit = RAND_MAX - (RAND_MAX % range);

if (isSync) {
// Sync API
while (true) {
const x = randomBytes(6).readUIntBE(0, 6);
// If x > (maxVal - (maxVal % range)), we will get "modulo bias"
if (x > randLimit) {
// Try again
if (x >= randLimit) {
// Try again.
continue;
}
const n = (x % range) + min;
return n;
return (x % range) + min;
}
} else {
// Async API
const pickAttempt = () => {
randomBytes(6, (err, bytes) => {
if (err) return callback(err);
const x = bytes.readUIntBE(0, 6);
// If x > (maxVal - (maxVal % range)), we will get "modulo bias"
if (x > randLimit) {
// Try again
if (x >= randLimit) {
// Try again.
return pickAttempt();
}
const n = (x % range) + min;
Expand Down