mirror of
https://github.com/louislam/uptime-kuma.git
synced 2025-08-21 02:34:11 +08:00
independent csprng solution
This commit is contained in:
66
src/util.ts
66
src/util.ts
@@ -8,7 +8,6 @@
|
||||
|
||||
import * as _dayjs from "dayjs";
|
||||
const dayjs = _dayjs;
|
||||
const crypto = require("crypto").webcrypto;
|
||||
|
||||
export const isDev = process.env.NODE_ENV === "development";
|
||||
export const appName = "Uptime Kuma";
|
||||
@@ -115,13 +114,64 @@ export function getRandomInt(min: number, max: number) {
|
||||
return Math.floor(Math.random() * (max - min + 1)) + min;
|
||||
}
|
||||
|
||||
export function getCryptoRandomInt(min: number, max: number) {
|
||||
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;
|
||||
/**
|
||||
* Returns either the NodeJS crypto.randomBytes() function or its
|
||||
* browser equivalent implemented via window.crypto.getRandomValues()
|
||||
*/
|
||||
let getRandomBytes = (
|
||||
(typeof window !== 'undefined' && window.crypto)
|
||||
|
||||
// Browsers
|
||||
? function () {
|
||||
return (numBytes: number) => {
|
||||
let randomBytes = new Uint8Array(numBytes);
|
||||
for (let i = 0; i < numBytes; i += 65536) {
|
||||
window.crypto.getRandomValues(randomBytes.subarray(i, i + Math.min(numBytes - i, 65536)));
|
||||
}
|
||||
return randomBytes;
|
||||
};
|
||||
}
|
||||
|
||||
// Node
|
||||
: function() {
|
||||
return require("crypto").randomBytes;
|
||||
}
|
||||
)();
|
||||
|
||||
export function getCryptoRandomInt(min: number, max: number):number {
|
||||
|
||||
// synchronous version of: https://github.com/joepie91/node-random-number-csprng
|
||||
|
||||
const range = max - min
|
||||
if (range >= Math.pow(2, 32))
|
||||
console.log("Warning! Range is too large.")
|
||||
|
||||
let tmpRange = range
|
||||
let bitsNeeded = 0
|
||||
let bytesNeeded = 0
|
||||
let mask = 1
|
||||
|
||||
while (tmpRange > 0) {
|
||||
if (bitsNeeded % 8 === 0) bytesNeeded += 1
|
||||
bitsNeeded += 1
|
||||
mask = mask << 1 | 1
|
||||
tmpRange = tmpRange >>> 1
|
||||
}
|
||||
|
||||
const randomBytes = getRandomBytes(bytesNeeded)
|
||||
let randomValue = 0
|
||||
|
||||
for (let i = 0; i < bytesNeeded; i++) {
|
||||
randomValue |= randomBytes[i] << 8 * i
|
||||
}
|
||||
|
||||
randomValue = randomValue & mask;
|
||||
|
||||
if (randomValue <= range) {
|
||||
return min + randomValue
|
||||
} else {
|
||||
return getCryptoRandomInt(min, max)
|
||||
}
|
||||
}
|
||||
|
||||
export function genSecret(length = 64) {
|
||||
|
Reference in New Issue
Block a user