2023-01-12 21:40:33 -07:00
|
|
|
import * as crypto from "node:crypto";
|
2020-03-29 08:16:36 -06:00
|
|
|
|
2023-01-12 21:40:33 -07:00
|
|
|
const L_CHARS = "0123456789abcdefghijklmnopqrstuvwxyz";
|
|
|
|
const LU_CHARS =
|
|
|
|
"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
2020-03-29 08:16:36 -06:00
|
|
|
|
|
|
|
export function secureRndstr(length = 32, useLU = true): string {
|
|
|
|
const chars = useLU ? LU_CHARS : L_CHARS;
|
|
|
|
const chars_len = chars.length;
|
|
|
|
|
2023-01-12 21:40:33 -07:00
|
|
|
let str = "";
|
2020-03-29 08:16:36 -06:00
|
|
|
|
|
|
|
for (let i = 0; i < length; i++) {
|
2023-01-12 21:40:33 -07:00
|
|
|
let rand = Math.floor(
|
|
|
|
(crypto.randomBytes(1).readUInt8(0) / 0xff) * chars_len,
|
|
|
|
);
|
2020-03-29 08:16:36 -06:00
|
|
|
if (rand === chars_len) {
|
|
|
|
rand = chars_len - 1;
|
|
|
|
}
|
|
|
|
str += chars.charAt(rand);
|
|
|
|
}
|
|
|
|
|
|
|
|
return str;
|
|
|
|
}
|