UNPKG

@csquare/random-bytes-seed

Version:

Zero-dep package to generate random bytes using a seed.

44 lines (43 loc) 1.6 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.randomBytesSeed = exports.options = void 0; const buffer_1 = require("buffer"); const crypto_1 = require("crypto"); /** * The default options. */ exports.options = { algorithm: 'sha256', seed: 'random-bytes-seed', }; /** * Generate random bytes and allow the final user to pass a seed for repeatability. * @param {number} length The random bytes desired length. * @param {Buffer | string} seed The seed. If not seed is provided, fallbacks to native {@link randomBytes}. * @return {Buffer} A pseudo random bytes buffer. */ function randomBytesSeed(length, seed) { // Validate the inputs if (typeof length !== 'number' || !Number.isInteger(length) || length < 1) { throw new TypeError('`length` argument must be a valid strictly positive integer.'); } if (!seed) { // No seed: fallback to native randomBytes return crypto_1.randomBytes(length); } /** * The round buffer, which is updated until the output buffer is long enough. */ let round = crypto_1.createHash('sha256').update(exports.options.seed).update(seed).digest(); /** * The output buffer, which size is increased after each round. */ let output = buffer_1.Buffer.alloc(0); while (output.length < length) { round = crypto_1.createHash('sha256').update(round).digest(); output = buffer_1.Buffer.concat([output, round]); } return output.slice(0, length); } exports.randomBytesSeed = randomBytesSeed; exports.default = randomBytesSeed;