Skip to content

Commit

Permalink
crypto: fix randomInt range check
Browse files Browse the repository at this point in the history
Refs: nodejs#34600

PR-URL: nodejs#35052
Reviewed-By: Richard Lau <[email protected]>
Reviewed-By: Denys Otrishko <[email protected]>
Reviewed-By: Colin Ihrig <[email protected]>
  • Loading branch information
tniessen authored and joesepi committed Oct 22, 2020
1 parent 9cfb68c commit 500838a
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 9 deletions.
4 changes: 2 additions & 2 deletions lib/internal/crypto/random.js
Original file line number Diff line number Diff line change
Expand Up @@ -149,8 +149,8 @@ function randomInt(min, max, callback) {
if (!NumberIsSafeInteger(max)) {
throw new ERR_INVALID_ARG_TYPE('max', 'safe integer', max);
}
if (!(max >= min)) {
throw new ERR_OUT_OF_RANGE('max', `>= ${min}`, max);
if (max <= min) {
throw new ERR_OUT_OF_RANGE('max', `> ${min}`, max);
}

// First we generate a random int between [0..range)
Expand Down
17 changes: 10 additions & 7 deletions test/parallel/test-crypto-random.js
Original file line number Diff line number Diff line change
Expand Up @@ -456,13 +456,16 @@ assert.throws(
}
);

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

const MAX_RANGE = 0xFFFF_FFFF_FFFF;
crypto.randomInt(MAX_RANGE, common.mustCall());
Expand Down

0 comments on commit 500838a

Please sign in to comment.