Skip to content

Commit a12d92c

Browse files
tniessenrichardlau
authored andcommitted
crypto: fix randomInt range check
Refs: #34600 PR-URL: #35052 Reviewed-By: Richard Lau <[email protected]> Reviewed-By: Denys Otrishko <[email protected]> Reviewed-By: Colin Ihrig <[email protected]>
1 parent f6b2286 commit a12d92c

File tree

2 files changed

+12
-9
lines changed

2 files changed

+12
-9
lines changed

lib/internal/crypto/random.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -149,8 +149,8 @@ function randomInt(min, max, callback) {
149149
if (!NumberIsSafeInteger(max)) {
150150
throw new ERR_INVALID_ARG_TYPE('max', 'safe integer', max);
151151
}
152-
if (!(max >= min)) {
153-
throw new ERR_OUT_OF_RANGE('max', `>= ${min}`, max);
152+
if (max <= min) {
153+
throw new ERR_OUT_OF_RANGE('max', `> ${min}`, max);
154154
}
155155

156156
// First we generate a random int between [0..range)

test/parallel/test-crypto-random.js

+10-7
Original file line numberDiff line numberDiff line change
@@ -456,13 +456,16 @@ assert.throws(
456456
}
457457
);
458458

459-
crypto.randomInt(0, common.mustCall());
460-
crypto.randomInt(0, 0, common.mustCall());
461-
assert.throws(() => crypto.randomInt(-1, common.mustNotCall()), {
462-
code: 'ERR_OUT_OF_RANGE',
463-
name: 'RangeError',
464-
message: 'The value of "max" is out of range. It must be >= 0. Received -1'
465-
});
459+
crypto.randomInt(1, common.mustCall());
460+
crypto.randomInt(0, 1, common.mustCall());
461+
for (const arg of [[0], [1, 1], [3, 2], [-5, -5], [11, -10]]) {
462+
assert.throws(() => crypto.randomInt(...arg, common.mustNotCall()), {
463+
code: 'ERR_OUT_OF_RANGE',
464+
name: 'RangeError',
465+
message: 'The value of "max" is out of range. It must be > ' +
466+
`${arg[arg.length - 2] || 0}. Received ${arg[arg.length - 1]}`
467+
});
468+
}
466469

467470
const MAX_RANGE = 0xFFFF_FFFF_FFFF;
468471
crypto.randomInt(MAX_RANGE, common.mustCall());

0 commit comments

Comments
 (0)