Update util.js

This commit is contained in:
Andreas Brett 2021-10-10 23:54:45 +02:00 committed by GitHub
parent 11bcd1e2ed
commit 0e6d7694ce
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -102,12 +102,21 @@ function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
exports.getRandomInt = getRandomInt;
function getCryptoRandomInt(min, max) {
const randomBuffer = new Uint32Array(1);
crypto.getRandomValues(randomBuffer);
const randomNumber = randomBuffer[0] / (0xffffffff + 1);
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(randomNumber * (max - min + 1)) + min;
}
exports.getCryptoRandomInt = getCryptoRandomInt;
function genSecret(length = 64) {
let secret = "";
let chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
let charsLength = chars.length;
for (let i = 0; i < length; i++) {
secret += chars.charAt(Math.floor(Math.random() * charsLength));
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
const charsLength = chars.length;
for ( let i = 0; i < length; i++ ) {
secret += chars.charAt(getCryptoRandomInt(0, charsLength));
}
return secret;
}