2025-06-21 23:30:33 +03:00

42 lines
1.5 KiB
JavaScript

"use strict";
// Copyright (C) 2016 Dmitry Chestnykh
// MIT License. See LICENSE file for details.
Object.defineProperty(exports, "__esModule", { value: true });
exports.NodeRandomSource = void 0;
const wipe_1 = require("@stablelib/wipe");
class NodeRandomSource {
constructor() {
this.isAvailable = false;
this.isInstantiated = false;
if (typeof require !== "undefined") {
const nodeCrypto = require("crypto");
if (nodeCrypto && nodeCrypto.randomBytes) {
this._crypto = nodeCrypto;
this.isAvailable = true;
this.isInstantiated = true;
}
}
}
randomBytes(length) {
if (!this.isAvailable || !this._crypto) {
throw new Error("Node.js random byte generator is not available.");
}
// Get random bytes (result is Buffer).
let buffer = this._crypto.randomBytes(length);
// Make sure we got the length that we requested.
if (buffer.length !== length) {
throw new Error("NodeRandomSource: got fewer bytes than requested");
}
// Allocate output array.
const out = new Uint8Array(length);
// Copy bytes from buffer to output.
for (let i = 0; i < out.length; i++) {
out[i] = buffer[i];
}
// Cleanup.
(0, wipe_1.wipe)(buffer);
return out;
}
}
exports.NodeRandomSource = NodeRandomSource;
//# sourceMappingURL=node.js.map