UNPKG

n-digit-token

Version:

Cryptographically secure pseudo-random token of n digits

26 lines (25 loc) 1.1 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.generateWithoutModuloBias = void 0; const calculateByteSize_1 = require("./calculateByteSize"); const calculateMax_1 = require("./calculateMax"); const generateSecureBytes_1 = require("./generateSecureBytes"); /** * Generates a cryptographically secure pseudo random token string of given length. * This implementation avoids modulo bias. * @param {number} length * @param {Options} [options] * @return {bigint} token */ const generateWithoutModuloBias = (length, options) => { const byteSize = (0, calculateByteSize_1.calculateByteSize)(length, options); const max = (0, calculateMax_1.calculateMax)({ byteSize, length }); let secureInt = 0n; do { secureInt = 0n; // minimize memory usage const secureBytes = (0, generateSecureBytes_1.generateSecureBytes)(byteSize, options); secureInt = BigInt('0x' + secureBytes); } while (secureInt > max); return secureInt % BigInt(10n ** BigInt(length)); }; exports.generateWithoutModuloBias = generateWithoutModuloBias;