From fd00fa2e9c06c4b05360c915fa44e2018c731503 Mon Sep 17 00:00:00 2001 From: =?utf8?q?J=C3=A9r=C3=B4me=20Benoit?= Date: Sat, 18 Sep 2021 09:50:53 +0200 Subject: [PATCH] Secure random integer generator inputs MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit Signed-off-by: Jérôme Benoit --- src/utils/Utils.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/utils/Utils.ts b/src/utils/Utils.ts index 8a89b578..a83fd4d5 100644 --- a/src/utils/Utils.ts +++ b/src/utils/Utils.ts @@ -98,12 +98,16 @@ export default class Utils { return result; } - public static getRandomFloat(max: number, min = 0): number { - return (crypto.randomBytes(4).readUInt32LE() / 0xffffffff) * (max - min) + min; + public static getRandomFloat(max: number, min = 0, negative = false): number { + const randomPositiveFloat = crypto.randomBytes(4).readUInt32LE() / 0xffffffff; + const sign = (negative && randomPositiveFloat < 0.5) ? 1 : -1; + return sign * (randomPositiveFloat * (max - min) + min); } public static getRandomInt(max: number, min = 0): number { + max = Math.floor(max); if (min) { + min = Math.ceil(min); return Math.floor(Utils.secureRandom() * (max - min + 1)) + min; } return Math.floor(Utils.secureRandom() * (max + 1)); -- 2.34.1