UNPKG

@signumjs/crypto

Version:

Cryptographic functions for building Signum Network apps.

55 lines 2.33 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.DefaultAlphabet = void 0; exports.getRandomBytes = getRandomBytes; exports.getRandomWords = getRandomWords; exports.getRandomString = getRandomString; const base_1 = require("./base"); function getRandomBytes(length) { return base_1.Crypto.adapter.getRandomValues(new Uint8Array(length)); } function getRandomWords(count, dictionary) { if (count > dictionary.length) { throw new Error('Too few words in dictionary'); } if (dictionary.length > 2 ** 32) { throw new Error('Dictionary must have less than 65536 words'); } const indices = new Set(); const mask = 2 ** 32 - (2 ** 32 % dictionary.length); const randomBytes = new Uint8Array(4); const cp = base_1.Crypto.adapter; while (indices.size < count) { cp.getRandomValues(randomBytes); const randomUint32 = ((randomBytes[0] << 24) | (randomBytes[1] << 16) | (randomBytes[2] << 8) | randomBytes[3]) >>> 0; const randomIndex = randomUint32 % dictionary.length; if (randomUint32 < mask) { indices.add(randomUint32 % dictionary.length); } } return Array.from(indices).map(index => dictionary[index]); } exports.DefaultAlphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; function getRandomString(length, alphabet = exports.DefaultAlphabet) { if (alphabet.length === 0) { throw new Error('Alphabet must not be empty.'); } const MaxLength = 65536; if (alphabet.length >= MaxLength) { throw new Error(`Alphabet is too large. Alphabet must be less than ${MaxLength} characters long.`); } const maxNonBiasedValue = Math.floor(MaxLength / alphabet.length) * alphabet.length; const indices = base_1.Crypto.adapter.getRandomValues(new Uint8Array(length * 2)); const uint16View = new Uint16Array(indices.buffer); let result = ''; for (let i = 0; i < length; i++) { let value = uint16View[i]; while (value >= maxNonBiasedValue) { const newBytes = base_1.Crypto.adapter.getRandomValues(new Uint8Array(2)); value = new Uint16Array(newBytes.buffer)[0]; } result += alphabet[value % alphabet.length]; } return result; } //# sourceMappingURL=random.js.map