From 13cf6891acf99e55fdb10bb769f651df5c19eb44 Mon Sep 17 00:00:00 2001 From: Andreas Brett Date: Sun, 10 Oct 2021 21:58:23 +0200 Subject: [PATCH] cryptographically strong secret generation generate TOTP secret using WebCrypto API (see https://github.com/louislam/uptime-kuma/issues/640) --- src/util.ts | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/src/util.ts b/src/util.ts index 6e911998..22279a7d 100644 --- a/src/util.ts +++ b/src/util.ts @@ -114,12 +114,21 @@ export function getRandomInt(min: number, max: number) { return Math.floor(Math.random() * (max - min + 1)) + min; } +export function getCryptoRandomInt(min, max) { + const randomBuffer = new Uint32Array(1); + crypto.getRandomValues(randomBuffer); + let randomNumber = randomBuffer[0] / (0xffffffff + 1); + min = Math.ceil(min); + max = Math.floor(max); + return Math.floor(randomNumber * (max - min + 1)) + min; +} + export 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 < 64; i++ ) { + secret += chars.charAt(getCryptoRandomInt(0, charsLength)); } return secret; }