From e6872e4f3b2652a89f347631cde5dfd1d0a32190 Mon Sep 17 00:00:00 2001 From: sugar Date: Sun, 12 Jan 2025 11:31:46 +0100 Subject: [PATCH] use uniform sampling in secure-rndstr the current implementation is biased towards making some characters 25% more common, with the default alphabet the more common characters being '0', '8', 'h', 'q', 'z', 'I', 'R', and 'Z' this changes the probability of all letters to be equal --- packages/backend/src/misc/secure-rndstr.ts | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/packages/backend/src/misc/secure-rndstr.ts b/packages/backend/src/misc/secure-rndstr.ts index 7853100d8..3da67826a 100644 --- a/packages/backend/src/misc/secure-rndstr.ts +++ b/packages/backend/src/misc/secure-rndstr.ts @@ -9,17 +9,9 @@ export const L_CHARS = '0123456789abcdefghijklmnopqrstuvwxyz'; const LU_CHARS = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; export function secureRndstr(length = 32, { chars = LU_CHARS } = {}): string { - const chars_len = chars.length; - let str = ''; - for (let i = 0; i < length; i++) { - let rand = Math.floor((crypto.randomBytes(1).readUInt8(0) / 0xFF) * chars_len); - if (rand === chars_len) { - rand = chars_len - 1; - } - str += chars.charAt(rand); + str += chars.charAt(crypto.randomInt(chars.length)); } - return str; } -- 2.45.2