From d2f116c6bb99e4de7778f152a874e750e46a45a8 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Wed, 7 Apr 2021 09:09:33 -0700 Subject: [PATCH] crypto: fixup randomFill size and offset handling MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: James M Snell PR-URL: https://github.com/nodejs/node/pull/38138 Fixes: https://github.com/nodejs/node/issues/38137 Reviewed-By: Anna Henningsen Reviewed-By: Tobias Nießen Reviewed-By: Darshan Sen Reviewed-By: Rich Trott Reviewed-By: Luigi Pinca --- lib/internal/crypto/random.js | 6 +++--- test/parallel/test-crypto-random.js | 7 +++++++ 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/lib/internal/crypto/random.js b/lib/internal/crypto/random.js index 88b535a357c4fa..e966074daa53c5 100644 --- a/lib/internal/crypto/random.js +++ b/lib/internal/crypto/random.js @@ -155,10 +155,11 @@ function randomFill(buf, offset, size, callback) { if (typeof offset === 'function') { callback = offset; offset = 0; - size = buf.bytesLength; + // Size is a length here, assertSize() call turns it into a number of bytes + size = buf.length; } else if (typeof size === 'function') { callback = size; - size = buf.byteLength - offset; + size = buf.length - offset; } else { validateCallback(callback); } @@ -176,7 +177,6 @@ function randomFill(buf, offset, size, callback) { return; } - // TODO(@jasnell): This is not yet handling byte offsets right const job = new RandomBytesJob( kCryptoJobAsync, buf, diff --git a/test/parallel/test-crypto-random.js b/test/parallel/test-crypto-random.js index 4f0c7dbb43f634..752bb8779f313d 100644 --- a/test/parallel/test-crypto-random.js +++ b/test/parallel/test-crypto-random.js @@ -525,3 +525,10 @@ assert.throws( assert.throws(() => crypto.randomInt(0, 1, i), cbError); }); } + +{ + // Verify that it doesn't throw or abort + crypto.randomFill(new Uint16Array(10), 0, common.mustSucceed()); + crypto.randomFill(new Uint32Array(10), 0, common.mustSucceed()); + crypto.randomFill(new Uint32Array(10), 0, 1, common.mustSucceed()); +}