use uniform sampling in secure-rndstr #33

Merged
sugar merged 1 commit from sugar/forkey:use-uniform-sampling-in-secure-rndstr into main 2025-01-17 14:22:11 +00:00
Showing only changes of commit e6872e4f3b - Show all commits

View file

@ -9,17 +9,9 @@ export const L_CHARS = '0123456789abcdefghijklmnopqrstuvwxyz';
const LU_CHARS = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; const LU_CHARS = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
export function secureRndstr(length = 32, { chars = LU_CHARS } = {}): string { export function secureRndstr(length = 32, { chars = LU_CHARS } = {}): string {
const chars_len = chars.length;
let str = ''; let str = '';
for (let i = 0; i < length; i++) { for (let i = 0; i < length; i++) {
let rand = Math.floor((crypto.randomBytes(1).readUInt8(0) / 0xFF) * chars_len); str += chars.charAt(crypto.randomInt(chars.length));
if (rand === chars_len) {
rand = chars_len - 1;
}
str += chars.charAt(rand);
} }
return str; return str;
} }