forked from woem.men/forkey
Merge pull request 'use uniform sampling in secure-rndstr' (#33) from sugar/forkey:use-uniform-sampling-in-secure-rndstr into main
Reviewed-on: woem.men/forkey#33 Reviewed-by: leah <leah@noreply.woem.men>
This commit is contained in:
commit
7c3eb990a6
1 changed files with 1 additions and 9 deletions
|
@ -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;
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue