From 99d76a65d58d151b760876e1e8e9178be3624365 Mon Sep 17 00:00:00 2001 From: =?utf8?q?J=C3=A9r=C3=B4me=20Benoit?= Date: Sun, 15 Jan 2023 16:46:15 +0100 Subject: [PATCH] Add crypto API randomInt() to random benchmarks MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit Signed-off-by: Jérôme Benoit --- benchmark-utils.js | 12 +++++++++++- random.js | 39 ++++++++++++++++++++++++++++++++++++--- 2 files changed, 47 insertions(+), 4 deletions(-) diff --git a/benchmark-utils.js b/benchmark-utils.js index 83d17ca..121ef4a 100644 --- a/benchmark-utils.js +++ b/benchmark-utils.js @@ -9,6 +9,15 @@ function secureRandom () { return crypto.randomBytes(4).readUInt32LE() / 0x100000000 } +/** + * Generate a cryptographically secure random number in the [0,1[ range + * + * @param + */ +function secureRandomWithRandomValues () { + return crypto.getRandomValues(new Uint32Array(1))[0] / 0x100000000 +} + /** * @param max * @param min @@ -95,5 +104,6 @@ module.exports = { generateRandomNumberArray, generateRandomObject, sleep, - secureRandom + secureRandom, + secureRandomWithRandomValues } diff --git a/random.js b/random.js index f4fd9f0..2bdd430 100644 --- a/random.js +++ b/random.js @@ -1,7 +1,11 @@ const Benchmark = require('benny') -const { secureRandom } = require('./benchmark-utils') +const { + secureRandom, + secureRandomWithRandomValues +} = require('./benchmark-utils') +const crypto = require('crypto') -const maximum = Number.MAX_SAFE_INTEGER +const maximum = 281474976710655 /** * @param max @@ -20,6 +24,26 @@ function getSecureRandomInteger (max = Number.MAX_SAFE_INTEGER, min = 0) { return Math.floor(secureRandom() * (max + 1)) } +/** + * @param max + * @param min + * @returns + */ +function getSecureRandomIntegerWithRandomValues ( + max = Number.MAX_SAFE_INTEGER, + min = 0 +) { + if (max < min || max < 0 || min < 0) { + throw new RangeError('Invalid interval') + } + max = Math.floor(max) + if (min != null && min !== 0) { + min = Math.ceil(min) + return Math.floor(secureRandomWithRandomValues() * (max - min + 1)) + min + } + return Math.floor(secureRandomWithRandomValues() * (max + 1)) +} + /** * @param max * @param min @@ -42,7 +66,16 @@ Benchmark.suite( Benchmark.add('Secure random integer generator', () => { getSecureRandomInteger(maximum) }), - Benchmark.add('Random integer generator', () => { + Benchmark.add( + 'Secure random with getRandomValues() integer generator', + () => { + getSecureRandomIntegerWithRandomValues(maximum) + } + ), + Benchmark.add('Crypto random integer generator', () => { + crypto.randomInt(maximum) + }), + Benchmark.add('Math random integer generator', () => { getRandomInteger(maximum) }), Benchmark.cycle(), -- 2.34.1