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
This commit is contained in:
sugar 2025-01-12 11:31:46 +01:00
parent b279f6e3d2
commit e6872e4f3b

View file

@ -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(crypto.randomInt(chars.length));
}
str += chars.charAt(rand);
}
return str;
}