From: Jérôme Benoit Date: Sat, 18 Sep 2021 07:50:53 +0000 (+0200) Subject: Secure random integer generator inputs X-Git-Tag: v1.1.3~4 X-Git-Url: https://git.piment-noir.org/?a=commitdiff_plain;h=fd00fa2e9c06c4b05360c915fa44e2018c731503;p=e-mobility-charging-stations-simulator.git Secure random integer generator inputs Signed-off-by: Jérôme Benoit --- 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));