トークン系の乱数ソースではcryptoを使うように (#6200)

This commit is contained in:
MeiMei
2020-03-29 23:16:36 +09:00
committed by GitHub
parent e2183400e5
commit 244ef0cb8f
5 changed files with 29 additions and 8 deletions

21
src/misc/secure-rndstr.ts Normal file
View File

@ -0,0 +1,21 @@
import * as crypto from 'crypto';
const L_CHARS = '0123456789abcdefghijklmnopqrstuvwxyz';
const LU_CHARS = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
export function secureRndstr(length = 32, useLU = true): string {
const chars = useLU ? LU_CHARS : L_CHARS;
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(rand);
}
return str;
}