forked from woem.men/forkey
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:
parent
b279f6e3d2
commit
e6872e4f3b
1 changed files with 1 additions and 9 deletions
|
@ -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;
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue