From 0e6d7694cebcc0ec752ebab701a895890a9363ef Mon Sep 17 00:00:00 2001 From: Andreas Brett Date: Sun, 10 Oct 2021 23:54:45 +0200 Subject: [PATCH] Update util.js --- src/util.js | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/src/util.js b/src/util.js index 7fb50c5b0..265ed51db 100644 --- a/src/util.js +++ b/src/util.js @@ -102,12 +102,21 @@ function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } exports.getRandomInt = getRandomInt; +function getCryptoRandomInt(min, max) { + const randomBuffer = new Uint32Array(1); + crypto.getRandomValues(randomBuffer); + const randomNumber = randomBuffer[0] / (0xffffffff + 1); + min = Math.ceil(min); + max = Math.floor(max); + return Math.floor(randomNumber * (max - min + 1)) + min; +} +exports.getCryptoRandomInt = getCryptoRandomInt; function genSecret(length = 64) { let secret = ""; - let chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; - let charsLength = chars.length; - for (let i = 0; i < length; i++) { - secret += chars.charAt(Math.floor(Math.random() * charsLength)); + const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + const charsLength = chars.length; + for ( let i = 0; i < length; i++ ) { + secret += chars.charAt(getCryptoRandomInt(0, charsLength)); } return secret; }