trng2
Version:
A True Random Number Generator (TRNG) module for Node.js that generates highly random data by combining multiple sources of entropy.
62 lines (42 loc) • 1.82 kB
JavaScript
/**
Copyright 2023 Bufferstack.IO Analytics Technology LLP, Pune
Licensed under the GNU General Public License, Version 3.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.gnu.org/licenses/gpl-3.0.html
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
**/
const crypto = require("crypto");
const randomly = Math.random();
function createEntropyBuffer() {
const timestamp = BigInt(new Date().getTime()) * BigInt(1000000);
const processEntropy = BigInt(process.hrtime.bigint() + BigInt(process.pid));
const mixedEntropy = timestamp ^ processEntropy;
const processBuffer = Buffer.allocUnsafe(8);
processBuffer.writeBigInt64BE(mixedEntropy);
return processBuffer;
}
function generate(callback) {
const byteLength = 8; // To generate 64 bits
const cryptoBuffer = crypto.randomBytes(byteLength);
const processBuffer = createEntropyBuffer();
const hash = crypto.createHash('sha512');
hash.update(cryptoBuffer);
hash.update(processBuffer);
const digestBuffer = hash.digest();
// Use only the first 8 bytes (64 bits) of the digest to create a number
const randomBuffer = digestBuffer.slice(0, 8);
// Convert the buffer to a BigInt
const randomNumber = BigInt('0x' + randomBuffer.toString('hex'));
// Normalize to [0, 1)
const maxPossibleNumber = BigInt(2) ** BigInt(64);
const normalizedNumber = Number(randomNumber) / Number(maxPossibleNumber);
callback(normalizedNumber);
}
module.exports = {
generate: generate
};