{ "version": 3, "sources": ["../node_modules/rfc4648/lib/index.js", "../node_modules/pvtsutils/build/index.js", "../node_modules/@cloudflare/voprf-ts/src/groupTypes.ts", "../node_modules/@cloudflare/voprf-ts/src/util.ts", "../node_modules/@cloudflare/voprf-ts/src/consts.ts", "../node_modules/@cloudflare/voprf-ts/src/oprf.ts", "../node_modules/@cloudflare/voprf-ts/lib/cjs/src/sjcl/index.js", "../node_modules/@cloudflare/voprf-ts/src/groupSjcl.ts", "../node_modules/@cloudflare/voprf-ts/src/cryptoSjcl.ts", "../node_modules/@cloudflare/voprf-ts/src/buildSettings.ts", "../node_modules/@cloudflare/voprf-ts/src/cryptoImpl.ts", "../node_modules/@cloudflare/voprf-ts/src/dleq.ts", "../node_modules/@cloudflare/voprf-ts/src/client.ts", "../node_modules/@cloudflare/voprf-ts/src/server.ts", "../node_modules/@cloudflare/voprf-ts/src/keys.ts", "../node_modules/@cloudflare/voprf-ts/src/index.ts", "../node_modules/rfc4648/lib/index.mjs", "../node_modules/@cloudflare/privacypass-ts/src/auth_scheme/rfc9110.ts", "../node_modules/asn1js/build/index.es.js", "../node_modules/pvutils/build/utils.es.js", "../node_modules/@cloudflare/privacypass-ts/src/util.ts", "../node_modules/@cloudflare/privacypass-ts/src/auth_scheme/private_token.ts", "../node_modules/@cloudflare/privacypass-ts/src/pub_verif_token.ts", "../node_modules/@cloudflare/blindrsa-ts/lib/src/sjcl/index.js", "../node_modules/@cloudflare/blindrsa-ts/src/util.ts", "../node_modules/@cloudflare/blindrsa-ts/src/blindrsa.ts", "../node_modules/@cloudflare/blindrsa-ts/src/prime.ts", "../node_modules/@cloudflare/blindrsa-ts/src/partially_blindrsa.ts", "../node_modules/@cloudflare/blindrsa-ts/src/index.ts", "../node_modules/@cloudflare/privacypass-ts/src/priv_verif_token.ts", "../node_modules/@cloudflare/privacypass-ts/src/issuance.ts", "../node_modules/@cloudflare/privacypass-ts/src/index.ts", "../src/client/index.ts"], "sourcesContent": ["'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\n/* eslint-disable @typescript-eslint/strict-boolean-expressions */\nfunction parse(string, encoding, opts) {\n var _opts$out;\n\n if (opts === void 0) {\n opts = {};\n }\n\n // Build the character lookup table:\n if (!encoding.codes) {\n encoding.codes = {};\n\n for (var i = 0; i < encoding.chars.length; ++i) {\n encoding.codes[encoding.chars[i]] = i;\n }\n } // The string must have a whole number of bytes:\n\n\n if (!opts.loose && string.length * encoding.bits & 7) {\n throw new SyntaxError('Invalid padding');\n } // Count the padding bytes:\n\n\n var end = string.length;\n\n while (string[end - 1] === '=') {\n --end; // If we get a whole number of bytes, there is too much padding:\n\n if (!opts.loose && !((string.length - end) * encoding.bits & 7)) {\n throw new SyntaxError('Invalid padding');\n }\n } // Allocate the output:\n\n\n var out = new ((_opts$out = opts.out) != null ? _opts$out : Uint8Array)(end * encoding.bits / 8 | 0); // Parse the data:\n\n var bits = 0; // Number of bits currently in the buffer\n\n var buffer = 0; // Bits waiting to be written out, MSB first\n\n var written = 0; // Next byte to write\n\n for (var _i = 0; _i < end; ++_i) {\n // Read one character from the string:\n var value = encoding.codes[string[_i]];\n\n if (value === undefined) {\n throw new SyntaxError('Invalid character ' + string[_i]);\n } // Append the bits to the buffer:\n\n\n buffer = buffer << encoding.bits | value;\n bits += encoding.bits; // Write out some bits if the buffer has a byte's worth:\n\n if (bits >= 8) {\n bits -= 8;\n out[written++] = 0xff & buffer >> bits;\n }\n } // Verify that we have received just enough bits:\n\n\n if (bits >= encoding.bits || 0xff & buffer << 8 - bits) {\n throw new SyntaxError('Unexpected end of data');\n }\n\n return out;\n}\nfunction stringify(data, encoding, opts) {\n if (opts === void 0) {\n opts = {};\n }\n\n var _opts = opts,\n _opts$pad = _opts.pad,\n pad = _opts$pad === void 0 ? true : _opts$pad;\n var mask = (1 << encoding.bits) - 1;\n var out = '';\n var bits = 0; // Number of bits currently in the buffer\n\n var buffer = 0; // Bits waiting to be written out, MSB first\n\n for (var i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = buffer << 8 | 0xff & data[i];\n bits += 8; // Write out as much as we can:\n\n while (bits > encoding.bits) {\n bits -= encoding.bits;\n out += encoding.chars[mask & buffer >> bits];\n }\n } // Partial character:\n\n\n if (bits) {\n out += encoding.chars[mask & buffer << encoding.bits - bits];\n } // Add padding characters until we hit a byte boundary:\n\n\n if (pad) {\n while (out.length * encoding.bits & 7) {\n out += '=';\n }\n }\n\n return out;\n}\n\n/* eslint-disable @typescript-eslint/strict-boolean-expressions */\nvar base16Encoding = {\n chars: '0123456789ABCDEF',\n bits: 4\n};\nvar base32Encoding = {\n chars: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',\n bits: 5\n};\nvar base32HexEncoding = {\n chars: '0123456789ABCDEFGHIJKLMNOPQRSTUV',\n bits: 5\n};\nvar base64Encoding = {\n chars: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n bits: 6\n};\nvar base64UrlEncoding = {\n chars: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bits: 6\n};\nvar base16 = {\n parse: function parse$1(string, opts) {\n return parse(string.toUpperCase(), base16Encoding, opts);\n },\n stringify: function stringify$1(data, opts) {\n return stringify(data, base16Encoding, opts);\n }\n};\nvar base32 = {\n parse: function parse$1(string, opts) {\n if (opts === void 0) {\n opts = {};\n }\n\n return parse(opts.loose ? string.toUpperCase().replace(/0/g, 'O').replace(/1/g, 'L').replace(/8/g, 'B') : string, base32Encoding, opts);\n },\n stringify: function stringify$1(data, opts) {\n return stringify(data, base32Encoding, opts);\n }\n};\nvar base32hex = {\n parse: function parse$1(string, opts) {\n return parse(string, base32HexEncoding, opts);\n },\n stringify: function stringify$1(data, opts) {\n return stringify(data, base32HexEncoding, opts);\n }\n};\nvar base64 = {\n parse: function parse$1(string, opts) {\n return parse(string, base64Encoding, opts);\n },\n stringify: function stringify$1(data, opts) {\n return stringify(data, base64Encoding, opts);\n }\n};\nvar base64url = {\n parse: function parse$1(string, opts) {\n return parse(string, base64UrlEncoding, opts);\n },\n stringify: function stringify$1(data, opts) {\n return stringify(data, base64UrlEncoding, opts);\n }\n};\nvar codec = {\n parse: parse,\n stringify: stringify\n};\n\nexports.base16 = base16;\nexports.base32 = base32;\nexports.base32hex = base32hex;\nexports.base64 = base64;\nexports.base64url = base64url;\nexports.codec = codec;\n", "/*!\n * MIT License\n * \n * Copyright (c) 2017-2022 Peculiar Ventures, LLC\n * \n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n * \n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n * \n */\n\n'use strict';\n\nconst ARRAY_BUFFER_NAME = \"[object ArrayBuffer]\";\nclass BufferSourceConverter {\n static isArrayBuffer(data) {\n return Object.prototype.toString.call(data) === ARRAY_BUFFER_NAME;\n }\n static toArrayBuffer(data) {\n if (this.isArrayBuffer(data)) {\n return data;\n }\n if (data.byteLength === data.buffer.byteLength) {\n return data.buffer;\n }\n if (data.byteOffset === 0 && data.byteLength === data.buffer.byteLength) {\n return data.buffer;\n }\n return this.toUint8Array(data.buffer)\n .slice(data.byteOffset, data.byteOffset + data.byteLength)\n .buffer;\n }\n static toUint8Array(data) {\n return this.toView(data, Uint8Array);\n }\n static toView(data, type) {\n if (data.constructor === type) {\n return data;\n }\n if (this.isArrayBuffer(data)) {\n return new type(data);\n }\n if (this.isArrayBufferView(data)) {\n return new type(data.buffer, data.byteOffset, data.byteLength);\n }\n throw new TypeError(\"The provided value is not of type '(ArrayBuffer or ArrayBufferView)'\");\n }\n static isBufferSource(data) {\n return this.isArrayBufferView(data)\n || this.isArrayBuffer(data);\n }\n static isArrayBufferView(data) {\n return ArrayBuffer.isView(data)\n || (data && this.isArrayBuffer(data.buffer));\n }\n static isEqual(a, b) {\n const aView = BufferSourceConverter.toUint8Array(a);\n const bView = BufferSourceConverter.toUint8Array(b);\n if (aView.length !== bView.byteLength) {\n return false;\n }\n for (let i = 0; i < aView.length; i++) {\n if (aView[i] !== bView[i]) {\n return false;\n }\n }\n return true;\n }\n static concat(...args) {\n let buffers;\n if (Array.isArray(args[0]) && !(args[1] instanceof Function)) {\n buffers = args[0];\n }\n else if (Array.isArray(args[0]) && args[1] instanceof Function) {\n buffers = args[0];\n }\n else {\n if (args[args.length - 1] instanceof Function) {\n buffers = args.slice(0, args.length - 1);\n }\n else {\n buffers = args;\n }\n }\n let size = 0;\n for (const buffer of buffers) {\n size += buffer.byteLength;\n }\n const res = new Uint8Array(size);\n let offset = 0;\n for (const buffer of buffers) {\n const view = this.toUint8Array(buffer);\n res.set(view, offset);\n offset += view.length;\n }\n if (args[args.length - 1] instanceof Function) {\n return this.toView(res, args[args.length - 1]);\n }\n return res.buffer;\n }\n}\n\nconst STRING_TYPE = \"string\";\nconst HEX_REGEX = /^[0-9a-f]+$/i;\nconst BASE64_REGEX = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;\nconst BASE64URL_REGEX = /^[a-zA-Z0-9-_]+$/;\nclass Utf8Converter {\n static fromString(text) {\n const s = unescape(encodeURIComponent(text));\n const uintArray = new Uint8Array(s.length);\n for (let i = 0; i < s.length; i++) {\n uintArray[i] = s.charCodeAt(i);\n }\n return uintArray.buffer;\n }\n static toString(buffer) {\n const buf = BufferSourceConverter.toUint8Array(buffer);\n let encodedString = \"\";\n for (let i = 0; i < buf.length; i++) {\n encodedString += String.fromCharCode(buf[i]);\n }\n const decodedString = decodeURIComponent(escape(encodedString));\n return decodedString;\n }\n}\nclass Utf16Converter {\n static toString(buffer, littleEndian = false) {\n const arrayBuffer = BufferSourceConverter.toArrayBuffer(buffer);\n const dataView = new DataView(arrayBuffer);\n let res = \"\";\n for (let i = 0; i < arrayBuffer.byteLength; i += 2) {\n const code = dataView.getUint16(i, littleEndian);\n res += String.fromCharCode(code);\n }\n return res;\n }\n static fromString(text, littleEndian = false) {\n const res = new ArrayBuffer(text.length * 2);\n const dataView = new DataView(res);\n for (let i = 0; i < text.length; i++) {\n dataView.setUint16(i * 2, text.charCodeAt(i), littleEndian);\n }\n return res;\n }\n}\nclass Convert {\n static isHex(data) {\n return typeof data === STRING_TYPE\n && HEX_REGEX.test(data);\n }\n static isBase64(data) {\n return typeof data === STRING_TYPE\n && BASE64_REGEX.test(data);\n }\n static isBase64Url(data) {\n return typeof data === STRING_TYPE\n && BASE64URL_REGEX.test(data);\n }\n static ToString(buffer, enc = \"utf8\") {\n const buf = BufferSourceConverter.toUint8Array(buffer);\n switch (enc.toLowerCase()) {\n case \"utf8\":\n return this.ToUtf8String(buf);\n case \"binary\":\n return this.ToBinary(buf);\n case \"hex\":\n return this.ToHex(buf);\n case \"base64\":\n return this.ToBase64(buf);\n case \"base64url\":\n return this.ToBase64Url(buf);\n case \"utf16le\":\n return Utf16Converter.toString(buf, true);\n case \"utf16\":\n case \"utf16be\":\n return Utf16Converter.toString(buf);\n default:\n throw new Error(`Unknown type of encoding '${enc}'`);\n }\n }\n static FromString(str, enc = \"utf8\") {\n if (!str) {\n return new ArrayBuffer(0);\n }\n switch (enc.toLowerCase()) {\n case \"utf8\":\n return this.FromUtf8String(str);\n case \"binary\":\n return this.FromBinary(str);\n case \"hex\":\n return this.FromHex(str);\n case \"base64\":\n return this.FromBase64(str);\n case \"base64url\":\n return this.FromBase64Url(str);\n case \"utf16le\":\n return Utf16Converter.fromString(str, true);\n case \"utf16\":\n case \"utf16be\":\n return Utf16Converter.fromString(str);\n default:\n throw new Error(`Unknown type of encoding '${enc}'`);\n }\n }\n static ToBase64(buffer) {\n const buf = BufferSourceConverter.toUint8Array(buffer);\n if (typeof btoa !== \"undefined\") {\n const binary = this.ToString(buf, \"binary\");\n return btoa(binary);\n }\n else {\n return Buffer.from(buf).toString(\"base64\");\n }\n }\n static FromBase64(base64) {\n const formatted = this.formatString(base64);\n if (!formatted) {\n return new ArrayBuffer(0);\n }\n if (!Convert.isBase64(formatted)) {\n throw new TypeError(\"Argument 'base64Text' is not Base64 encoded\");\n }\n if (typeof atob !== \"undefined\") {\n return this.FromBinary(atob(formatted));\n }\n else {\n return new Uint8Array(Buffer.from(formatted, \"base64\")).buffer;\n }\n }\n static FromBase64Url(base64url) {\n const formatted = this.formatString(base64url);\n if (!formatted) {\n return new ArrayBuffer(0);\n }\n if (!Convert.isBase64Url(formatted)) {\n throw new TypeError(\"Argument 'base64url' is not Base64Url encoded\");\n }\n return this.FromBase64(this.Base64Padding(formatted.replace(/\\-/g, \"+\").replace(/\\_/g, \"/\")));\n }\n static ToBase64Url(data) {\n return this.ToBase64(data).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/\\=/g, \"\");\n }\n static FromUtf8String(text, encoding = Convert.DEFAULT_UTF8_ENCODING) {\n switch (encoding) {\n case \"ascii\":\n return this.FromBinary(text);\n case \"utf8\":\n return Utf8Converter.fromString(text);\n case \"utf16\":\n case \"utf16be\":\n return Utf16Converter.fromString(text);\n case \"utf16le\":\n case \"usc2\":\n return Utf16Converter.fromString(text, true);\n default:\n throw new Error(`Unknown type of encoding '${encoding}'`);\n }\n }\n static ToUtf8String(buffer, encoding = Convert.DEFAULT_UTF8_ENCODING) {\n switch (encoding) {\n case \"ascii\":\n return this.ToBinary(buffer);\n case \"utf8\":\n return Utf8Converter.toString(buffer);\n case \"utf16\":\n case \"utf16be\":\n return Utf16Converter.toString(buffer);\n case \"utf16le\":\n case \"usc2\":\n return Utf16Converter.toString(buffer, true);\n default:\n throw new Error(`Unknown type of encoding '${encoding}'`);\n }\n }\n static FromBinary(text) {\n const stringLength = text.length;\n const resultView = new Uint8Array(stringLength);\n for (let i = 0; i < stringLength; i++) {\n resultView[i] = text.charCodeAt(i);\n }\n return resultView.buffer;\n }\n static ToBinary(buffer) {\n const buf = BufferSourceConverter.toUint8Array(buffer);\n let res = \"\";\n for (let i = 0; i < buf.length; i++) {\n res += String.fromCharCode(buf[i]);\n }\n return res;\n }\n static ToHex(buffer) {\n const buf = BufferSourceConverter.toUint8Array(buffer);\n let result = \"\";\n const len = buf.length;\n for (let i = 0; i < len; i++) {\n const byte = buf[i];\n if (byte < 16) {\n result += \"0\";\n }\n result += byte.toString(16);\n }\n return result;\n }\n static FromHex(hexString) {\n let formatted = this.formatString(hexString);\n if (!formatted) {\n return new ArrayBuffer(0);\n }\n if (!Convert.isHex(formatted)) {\n throw new TypeError(\"Argument 'hexString' is not HEX encoded\");\n }\n if (formatted.length % 2) {\n formatted = `0${formatted}`;\n }\n const res = new Uint8Array(formatted.length / 2);\n for (let i = 0; i < formatted.length; i = i + 2) {\n const c = formatted.slice(i, i + 2);\n res[i / 2] = parseInt(c, 16);\n }\n return res.buffer;\n }\n static ToUtf16String(buffer, littleEndian = false) {\n return Utf16Converter.toString(buffer, littleEndian);\n }\n static FromUtf16String(text, littleEndian = false) {\n return Utf16Converter.fromString(text, littleEndian);\n }\n static Base64Padding(base64) {\n const padCount = 4 - (base64.length % 4);\n if (padCount < 4) {\n for (let i = 0; i < padCount; i++) {\n base64 += \"=\";\n }\n }\n return base64;\n }\n static formatString(data) {\n return (data === null || data === void 0 ? void 0 : data.replace(/[\\n\\r\\t ]/g, \"\")) || \"\";\n }\n}\nConvert.DEFAULT_UTF8_ENCODING = \"utf8\";\n\nfunction assign(target, ...sources) {\n const res = arguments[0];\n for (let i = 1; i < arguments.length; i++) {\n const obj = arguments[i];\n for (const prop in obj) {\n res[prop] = obj[prop];\n }\n }\n return res;\n}\nfunction combine(...buf) {\n const totalByteLength = buf.map((item) => item.byteLength).reduce((prev, cur) => prev + cur);\n const res = new Uint8Array(totalByteLength);\n let currentPos = 0;\n buf.map((item) => new Uint8Array(item)).forEach((arr) => {\n for (const item2 of arr) {\n res[currentPos++] = item2;\n }\n });\n return res.buffer;\n}\nfunction isEqual(bytes1, bytes2) {\n if (!(bytes1 && bytes2)) {\n return false;\n }\n if (bytes1.byteLength !== bytes2.byteLength) {\n return false;\n }\n const b1 = new Uint8Array(bytes1);\n const b2 = new Uint8Array(bytes2);\n for (let i = 0; i < bytes1.byteLength; i++) {\n if (b1[i] !== b2[i]) {\n return false;\n }\n }\n return true;\n}\n\nexports.BufferSourceConverter = BufferSourceConverter;\nexports.Convert = Convert;\nexports.assign = assign;\nexports.combine = combine;\nexports.isEqual = isEqual;\n", null, null, null, null, "/** @fileOverview Javascript cryptography implementation.\n *\n * Crush to remove comments, shorten variable names and\n * generally reduce transmission size.\n *\n * @author Emily Stark\n * @author Mike Hamburg\n * @author Dan Boneh\n */\n\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/*jslint indent: 2, bitwise: false, nomen: false, plusplus: false, white: false, regexp: false */\n/*global document, window, escape, unescape, module, require, Uint32Array */\n/**\n * The Stanford Javascript Crypto Library, top-level namespace.\n * @namespace\n */\nvar sjcl = {\n /**\n * Symmetric ciphers.\n * @namespace\n */\n cipher: {},\n /**\n * Hash functions. Right now only SHA256 is implemented.\n * @namespace\n */\n hash: {},\n /**\n * Key exchange functions. Right now only SRP is implemented.\n * @namespace\n */\n keyexchange: {},\n /**\n * Cipher modes of operation.\n * @namespace\n */\n mode: {},\n /**\n * Miscellaneous. HMAC and PBKDF2.\n * @namespace\n */\n misc: {},\n /**\n * Bit array encoders and decoders.\n * @namespace\n *\n * @description\n * The members of this namespace are functions which translate between\n * SJCL's bitArrays and other objects (usually strings). Because it\n * isn't always clear which direction is encoding and which is decoding,\n * the method names are \"fromBits\" and \"toBits\".\n */\n codec: {},\n /**\n * Exceptions.\n * @namespace\n */\n exception: {\n /**\n * Ciphertext is corrupt.\n * @constructor\n */\n corrupt: function (message) {\n this.toString = function () { return \"CORRUPT: \" + this.message; };\n this.message = message;\n },\n /**\n * Invalid parameter.\n * @constructor\n */\n invalid: function (message) {\n this.toString = function () { return \"INVALID: \" + this.message; };\n this.message = message;\n },\n /**\n * Bug or missing feature in SJCL.\n * @constructor\n */\n bug: function (message) {\n this.toString = function () { return \"BUG: \" + this.message; };\n this.message = message;\n },\n /**\n * Something isn't ready.\n * @constructor\n */\n notReady: function (message) {\n this.toString = function () { return \"NOT READY: \" + this.message; };\n this.message = message;\n }\n }\n};\n/** @fileOverview Low-level AES implementation.\n *\n * This file contains a low-level implementation of AES, optimized for\n * size and for efficiency on several browsers. It is based on\n * OpenSSL's aes_core.c, a public-domain implementation by Vincent\n * Rijmen, Antoon Bosselaers and Paulo Barreto.\n *\n * An older version of this implementation is available in the public\n * domain, but this one is (c) Emily Stark, Mike Hamburg, Dan Boneh,\n * Stanford University 2008-2010 and BSD-licensed for liability\n * reasons.\n *\n * @author Emily Stark\n * @author Mike Hamburg\n * @author Dan Boneh\n */\n/**\n * Schedule out an AES key for both encryption and decryption. This\n * is a low-level class. Use a cipher mode to do bulk encryption.\n *\n * @constructor\n * @param {Array} key The key as an array of 4, 6 or 8 words.\n */\nsjcl.cipher.aes = function (key) {\n if (!this._tables[0][0][0]) {\n this._precompute();\n }\n var i, j, tmp, encKey, decKey, sbox = this._tables[0][4], decTable = this._tables[1], keyLen = key.length, rcon = 1;\n if (keyLen !== 4 && keyLen !== 6 && keyLen !== 8) {\n throw new sjcl.exception.invalid(\"invalid aes key size\");\n }\n this._key = [encKey = key.slice(0), decKey = []];\n // schedule encryption keys\n for (i = keyLen; i < 4 * keyLen + 28; i++) {\n tmp = encKey[i - 1];\n // apply sbox\n if (i % keyLen === 0 || (keyLen === 8 && i % keyLen === 4)) {\n tmp = sbox[tmp >>> 24] << 24 ^ sbox[tmp >> 16 & 255] << 16 ^ sbox[tmp >> 8 & 255] << 8 ^ sbox[tmp & 255];\n // shift rows and add rcon\n if (i % keyLen === 0) {\n tmp = tmp << 8 ^ tmp >>> 24 ^ rcon << 24;\n rcon = rcon << 1 ^ (rcon >> 7) * 283;\n }\n }\n encKey[i] = encKey[i - keyLen] ^ tmp;\n }\n // schedule decryption keys\n for (j = 0; i; j++, i--) {\n tmp = encKey[j & 3 ? i : i - 4];\n if (i <= 4 || j < 4) {\n decKey[j] = tmp;\n }\n else {\n decKey[j] = decTable[0][sbox[tmp >>> 24]] ^\n decTable[1][sbox[tmp >> 16 & 255]] ^\n decTable[2][sbox[tmp >> 8 & 255]] ^\n decTable[3][sbox[tmp & 255]];\n }\n }\n};\nsjcl.cipher.aes.prototype = {\n // public\n /* Something like this might appear here eventually\n name: \"AES\",\n blockSize: 4,\n keySizes: [4,6,8],\n */\n /**\n * Encrypt an array of 4 big-endian words.\n * @param {Array} data The plaintext.\n * @return {Array} The ciphertext.\n */\n encrypt: function (data) { return this._crypt(data, 0); },\n /**\n * Decrypt an array of 4 big-endian words.\n * @param {Array} data The ciphertext.\n * @return {Array} The plaintext.\n */\n decrypt: function (data) { return this._crypt(data, 1); },\n /**\n * The expanded S-box and inverse S-box tables. These will be computed\n * on the client so that we don't have to send them down the wire.\n *\n * There are two tables, _tables[0] is for encryption and\n * _tables[1] is for decryption.\n *\n * The first 4 sub-tables are the expanded S-box with MixColumns. The\n * last (_tables[01][4]) is the S-box itself.\n *\n * @private\n */\n _tables: [[[], [], [], [], []], [[], [], [], [], []]],\n /**\n * Expand the S-box tables.\n *\n * @private\n */\n _precompute: function () {\n var encTable = this._tables[0], decTable = this._tables[1], sbox = encTable[4], sboxInv = decTable[4], i, x, xInv, d = [], th = [], x2, x4, x8, s, tEnc, tDec;\n // Compute double and third tables\n for (i = 0; i < 256; i++) {\n th[(d[i] = i << 1 ^ (i >> 7) * 283) ^ i] = i;\n }\n for (x = xInv = 0; !sbox[x]; x ^= x2 || 1, xInv = th[xInv] || 1) {\n // Compute sbox\n s = xInv ^ xInv << 1 ^ xInv << 2 ^ xInv << 3 ^ xInv << 4;\n s = s >> 8 ^ s & 255 ^ 99;\n sbox[x] = s;\n sboxInv[s] = x;\n // Compute MixColumns\n x8 = d[x4 = d[x2 = d[x]]];\n tDec = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;\n tEnc = d[s] * 0x101 ^ s * 0x1010100;\n for (i = 0; i < 4; i++) {\n encTable[i][x] = tEnc = tEnc << 24 ^ tEnc >>> 8;\n decTable[i][s] = tDec = tDec << 24 ^ tDec >>> 8;\n }\n }\n // Compactify. Considerable speedup on Firefox.\n for (i = 0; i < 5; i++) {\n encTable[i] = encTable[i].slice(0);\n decTable[i] = decTable[i].slice(0);\n }\n },\n /**\n * Encryption and decryption core.\n * @param {Array} input Four words to be encrypted or decrypted.\n * @param dir The direction, 0 for encrypt and 1 for decrypt.\n * @return {Array} The four encrypted or decrypted words.\n * @private\n */\n _crypt: function (input, dir) {\n if (input.length !== 4) {\n throw new sjcl.exception.invalid(\"invalid aes block size\");\n }\n var key = this._key[dir], \n // state variables a,b,c,d are loaded with pre-whitened data\n a = input[0] ^ key[0], b = input[dir ? 3 : 1] ^ key[1], c = input[2] ^ key[2], d = input[dir ? 1 : 3] ^ key[3], a2, b2, c2, nInnerRounds = key.length / 4 - 2, i, kIndex = 4, out = [0, 0, 0, 0], table = this._tables[dir], \n // load up the tables\n t0 = table[0], t1 = table[1], t2 = table[2], t3 = table[3], sbox = table[4];\n // Inner rounds. Cribbed from OpenSSL.\n for (i = 0; i < nInnerRounds; i++) {\n a2 = t0[a >>> 24] ^ t1[b >> 16 & 255] ^ t2[c >> 8 & 255] ^ t3[d & 255] ^ key[kIndex];\n b2 = t0[b >>> 24] ^ t1[c >> 16 & 255] ^ t2[d >> 8 & 255] ^ t3[a & 255] ^ key[kIndex + 1];\n c2 = t0[c >>> 24] ^ t1[d >> 16 & 255] ^ t2[a >> 8 & 255] ^ t3[b & 255] ^ key[kIndex + 2];\n d = t0[d >>> 24] ^ t1[a >> 16 & 255] ^ t2[b >> 8 & 255] ^ t3[c & 255] ^ key[kIndex + 3];\n kIndex += 4;\n a = a2;\n b = b2;\n c = c2;\n }\n // Last round.\n for (i = 0; i < 4; i++) {\n out[dir ? 3 & -i : i] =\n sbox[a >>> 24] << 24 ^\n sbox[b >> 16 & 255] << 16 ^\n sbox[c >> 8 & 255] << 8 ^\n sbox[d & 255] ^\n key[kIndex++];\n a2 = a;\n a = b;\n b = c;\n c = d;\n d = a2;\n }\n return out;\n }\n};\n/** @fileOverview Arrays of bits, encoded as arrays of Numbers.\n *\n * @author Emily Stark\n * @author Mike Hamburg\n * @author Dan Boneh\n */\n/**\n * Arrays of bits, encoded as arrays of Numbers.\n * @namespace\n * @description\n *
\n * These objects are the currency accepted by SJCL's crypto functions.\n *
\n *\n *\n * Most of our crypto primitives operate on arrays of 4-byte words internally,\n * but many of them can take arguments that are not a multiple of 4 bytes.\n * This library encodes arrays of bits (whose size need not be a multiple of 8\n * bits) as arrays of 32-bit words. The bits are packed, big-endian, into an\n * array of words, 32 bits at a time. Since the words are double-precision\n * floating point numbers, they fit some extra data. We use this (in a private,\n * possibly-changing manner) to encode the number of bits actually present\n * in the last word of the array.\n *
\n *\n *\n * Because bitwise ops clear this out-of-band data, these arrays can be passed\n * to ciphers like AES which want arrays of words.\n *
\n */\nsjcl.bitArray = {\n /**\n * Array slices in units of bits.\n * @param {bitArray} a The array to slice.\n * @param {Number} bstart The offset to the start of the slice, in bits.\n * @param {Number} bend The offset to the end of the slice, in bits. If this is undefined,\n * slice until the end of the array.\n * @return {bitArray} The requested slice.\n */\n bitSlice: function (a, bstart, bend) {\n a = sjcl.bitArray._shiftRight(a.slice(bstart / 32), 32 - (bstart & 31)).slice(1);\n return (bend === undefined) ? a : sjcl.bitArray.clamp(a, bend - bstart);\n },\n /**\n * Extract a number packed into a bit array.\n * @param {bitArray} a The array to slice.\n * @param {Number} bstart The offset to the start of the slice, in bits.\n * @param {Number} blength The length of the number to extract.\n * @return {Number} The requested slice.\n */\n extract: function (a, bstart, blength) {\n // FIXME: this Math.floor is not necessary at all, but for some reason\n // seems to suppress a bug in the Chromium JIT.\n var x, sh = Math.floor((-bstart - blength) & 31);\n if ((bstart + blength - 1 ^ bstart) & -32) {\n // it crosses a boundary\n x = (a[bstart / 32 | 0] << (32 - sh)) ^ (a[bstart / 32 + 1 | 0] >>> sh);\n }\n else {\n // within a single word\n x = a[bstart / 32 | 0] >>> sh;\n }\n return x & ((1 << blength) - 1);\n },\n /**\n * Concatenate two bit arrays.\n * @param {bitArray} a1 The first array.\n * @param {bitArray} a2 The second array.\n * @return {bitArray} The concatenation of a1 and a2.\n */\n concat: function (a1, a2) {\n if (a1.length === 0 || a2.length === 0) {\n return a1.concat(a2);\n }\n var last = a1[a1.length - 1], shift = sjcl.bitArray.getPartial(last);\n if (shift === 32) {\n return a1.concat(a2);\n }\n else {\n return sjcl.bitArray._shiftRight(a2, shift, last | 0, a1.slice(0, a1.length - 1));\n }\n },\n /**\n * Find the length of an array of bits.\n * @param {bitArray} a The array.\n * @return {Number} The length of a, in bits.\n */\n bitLength: function (a) {\n var l = a.length, x;\n if (l === 0) {\n return 0;\n }\n x = a[l - 1];\n return (l - 1) * 32 + sjcl.bitArray.getPartial(x);\n },\n /**\n * Truncate an array.\n * @param {bitArray} a The array.\n * @param {Number} len The length to truncate to, in bits.\n * @return {bitArray} A new array, truncated to len bits.\n */\n clamp: function (a, len) {\n if (a.length * 32 < len) {\n return a;\n }\n a = a.slice(0, Math.ceil(len / 32));\n var l = a.length;\n len = len & 31;\n if (l > 0 && len) {\n a[l - 1] = sjcl.bitArray.partial(len, a[l - 1] & 0x80000000 >> (len - 1), 1);\n }\n return a;\n },\n /**\n * Make a partial word for a bit array.\n * @param {Number} len The number of bits in the word.\n * @param {Number} x The bits.\n * @param {Number} [_end=0] Pass 1 if x has already been shifted to the high side.\n * @return {Number} The partial word.\n */\n partial: function (len, x, _end) {\n if (len === 32) {\n return x;\n }\n return (_end ? x | 0 : x << (32 - len)) + len * 0x10000000000;\n },\n /**\n * Get the number of bits used by a partial word.\n * @param {Number} x The partial word.\n * @return {Number} The number of bits used by the partial word.\n */\n getPartial: function (x) {\n return Math.round(x / 0x10000000000) || 32;\n },\n /**\n * Compare two arrays for equality in a predictable amount of time.\n * @param {bitArray} a The first array.\n * @param {bitArray} b The second array.\n * @return {boolean} true if a == b; false otherwise.\n */\n equal: function (a, b) {\n if (sjcl.bitArray.bitLength(a) !== sjcl.bitArray.bitLength(b)) {\n return false;\n }\n var x = 0, i;\n for (i = 0; i < a.length; i++) {\n x |= a[i] ^ b[i];\n }\n return (x === 0);\n },\n /** Shift an array right.\n * @param {bitArray} a The array to shift.\n * @param {Number} shift The number of bits to shift.\n * @param {Number} [carry=0] A byte to carry in\n * @param {bitArray} [out=[]] An array to prepend to the output.\n * @private\n */\n _shiftRight: function (a, shift, carry, out) {\n var i, last2 = 0, shift2;\n if (out === undefined) {\n out = [];\n }\n for (; shift >= 32; shift -= 32) {\n out.push(carry);\n carry = 0;\n }\n if (shift === 0) {\n return out.concat(a);\n }\n for (i = 0; i < a.length; i++) {\n out.push(carry | a[i] >>> shift);\n carry = a[i] << (32 - shift);\n }\n last2 = a.length ? a[a.length - 1] : 0;\n shift2 = sjcl.bitArray.getPartial(last2);\n out.push(sjcl.bitArray.partial(shift + shift2 & 31, (shift + shift2 > 32) ? carry : out.pop(), 1));\n return out;\n },\n /** xor a block of 4 words together.\n * @private\n */\n _xor4: function (x, y) {\n return [x[0] ^ y[0], x[1] ^ y[1], x[2] ^ y[2], x[3] ^ y[3]];\n },\n /** byteswap a word array inplace.\n * (does not handle partial words)\n * @param {sjcl.bitArray} a word array\n * @return {sjcl.bitArray} byteswapped array\n */\n byteswapM: function (a) {\n var i, v, m = 0xff00;\n for (i = 0; i < a.length; ++i) {\n v = a[i];\n a[i] = (v >>> 24) | ((v >>> 8) & m) | ((v & m) << 8) | (v << 24);\n }\n return a;\n }\n};\n/** @fileOverview Bit array codec implementations.\n *\n * @author Emily Stark\n * @author Mike Hamburg\n * @author Dan Boneh\n */\n/**\n * UTF-8 strings\n * @namespace\n */\nsjcl.codec.utf8String = {\n /** Convert from a bitArray to a UTF-8 string. */\n fromBits: function (arr) {\n var out = \"\", bl = sjcl.bitArray.bitLength(arr), i, tmp;\n for (i = 0; i < bl / 8; i++) {\n if ((i & 3) === 0) {\n tmp = arr[i / 4];\n }\n out += String.fromCharCode(tmp >>> 8 >>> 8 >>> 8);\n tmp <<= 8;\n }\n return decodeURIComponent(escape(out));\n },\n /** Convert from a UTF-8 string to a bitArray. */\n toBits: function (str) {\n str = unescape(encodeURIComponent(str));\n var out = [], i, tmp = 0;\n for (i = 0; i < str.length; i++) {\n tmp = tmp << 8 | str.charCodeAt(i);\n if ((i & 3) === 3) {\n out.push(tmp);\n tmp = 0;\n }\n }\n if (i & 3) {\n out.push(sjcl.bitArray.partial(8 * (i & 3), tmp));\n }\n return out;\n }\n};\n/** @fileOverview Bit array codec implementations.\n *\n * @author Emily Stark\n * @author Mike Hamburg\n * @author Dan Boneh\n */\n/**\n * Hexadecimal\n * @namespace\n */\nsjcl.codec.hex = {\n /** Convert from a bitArray to a hex string. */\n fromBits: function (arr) {\n var out = \"\", i;\n for (i = 0; i < arr.length; i++) {\n out += ((arr[i] | 0) + 0xF00000000000).toString(16).substr(4);\n }\n return out.substr(0, sjcl.bitArray.bitLength(arr) / 4); //.replace(/(.{8})/g, \"$1 \");\n },\n /** Convert from a hex string to a bitArray. */\n toBits: function (str) {\n var i, out = [], len;\n str = str.replace(/\\s|0x/g, \"\");\n len = str.length;\n str = str + \"00000000\";\n for (i = 0; i < str.length; i += 8) {\n out.push(parseInt(str.substr(i, 8), 16) ^ 0);\n }\n return sjcl.bitArray.clamp(out, len * 4);\n }\n};\n/** @fileOverview Bit array codec implementations.\n *\n * @author Emily Stark\n * @author Mike Hamburg\n * @author Dan Boneh\n */\n/**\n * Base64 encoding/decoding\n * @namespace\n */\nsjcl.codec.base64 = {\n /** The base64 alphabet.\n * @private\n */\n _chars: \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\",\n /** Convert from a bitArray to a base64 string. */\n fromBits: function (arr, _noEquals, _url) {\n var out = \"\", i, bits = 0, c = sjcl.codec.base64._chars, ta = 0, bl = sjcl.bitArray.bitLength(arr);\n if (_url) {\n c = c.substr(0, 62) + '-_';\n }\n for (i = 0; out.length * 6 < bl;) {\n out += c.charAt((ta ^ arr[i] >>> bits) >>> 26);\n if (bits < 6) {\n ta = arr[i] << (6 - bits);\n bits += 26;\n i++;\n }\n else {\n ta <<= 6;\n bits -= 6;\n }\n }\n while ((out.length & 3) && !_noEquals) {\n out += \"=\";\n }\n return out;\n },\n /** Convert from a base64 string to a bitArray */\n toBits: function (str, _url) {\n str = str.replace(/\\s|=/g, '');\n var out = [], i, bits = 0, c = sjcl.codec.base64._chars, ta = 0, x;\n if (_url) {\n c = c.substr(0, 62) + '-_';\n }\n for (i = 0; i < str.length; i++) {\n x = c.indexOf(str.charAt(i));\n if (x < 0) {\n throw new sjcl.exception.invalid(\"this isn't base64!\");\n }\n if (bits > 26) {\n bits -= 26;\n out.push(ta ^ x >>> bits);\n ta = x << (32 - bits);\n }\n else {\n bits += 6;\n ta ^= x << (32 - bits);\n }\n }\n if (bits & 56) {\n out.push(sjcl.bitArray.partial(bits & 56, ta, 1));\n }\n return out;\n }\n};\nsjcl.codec.base64url = {\n fromBits: function (arr) { return sjcl.codec.base64.fromBits(arr, 1, 1); },\n toBits: function (str) { return sjcl.codec.base64.toBits(str, 1); }\n};\n/** @fileOverview Bit array codec implementations.\n *\n * @author Emily Stark\n * @author Mike Hamburg\n * @author Dan Boneh\n */\n/**\n * Arrays of bytes\n * @namespace\n */\nsjcl.codec.bytes = {\n /** Convert from a bitArray to an array of bytes. */\n fromBits: function (arr) {\n var out = [], bl = sjcl.bitArray.bitLength(arr), i, tmp;\n for (i = 0; i < bl / 8; i++) {\n if ((i & 3) === 0) {\n tmp = arr[i / 4];\n }\n out.push(tmp >>> 24);\n tmp <<= 8;\n }\n return out;\n },\n /** Convert from an array of bytes to a bitArray. */\n toBits: function (bytes) {\n var out = [], i, tmp = 0;\n for (i = 0; i < bytes.length; i++) {\n tmp = tmp << 8 | bytes[i];\n if ((i & 3) === 3) {\n out.push(tmp);\n tmp = 0;\n }\n }\n if (i & 3) {\n out.push(sjcl.bitArray.partial(8 * (i & 3), tmp));\n }\n return out;\n }\n};\n/** @fileOverview Javascript SHA-256 implementation.\n *\n * An older version of this implementation is available in the public\n * domain, but this one is (c) Emily Stark, Mike Hamburg, Dan Boneh,\n * Stanford University 2008-2010 and BSD-licensed for liability\n * reasons.\n *\n * Special thanks to Aldo Cortesi for pointing out several bugs in\n * this code.\n *\n * @author Emily Stark\n * @author Mike Hamburg\n * @author Dan Boneh\n */\n/**\n * Context for a SHA-256 operation in progress.\n * @constructor\n */\nsjcl.hash.sha256 = function (hash) {\n if (!this._key[0]) {\n this._precompute();\n }\n if (hash) {\n this._h = hash._h.slice(0);\n this._buffer = hash._buffer.slice(0);\n this._length = hash._length;\n }\n else {\n this.reset();\n }\n};\n/**\n * Hash a string or an array of words.\n * @static\n * @param {bitArray|String} data the data to hash.\n * @return {bitArray} The hash value, an array of 16 big-endian words.\n */\nsjcl.hash.sha256.hash = function (data) {\n return (new sjcl.hash.sha256()).update(data).finalize();\n};\nsjcl.hash.sha256.prototype = {\n /**\n * The hash's block size, in bits.\n * @constant\n */\n blockSize: 512,\n /**\n * Reset the hash state.\n * @return this\n */\n reset: function () {\n this._h = this._init.slice(0);\n this._buffer = [];\n this._length = 0;\n return this;\n },\n /**\n * Input several words to the hash.\n * @param {bitArray|String} data the data to hash.\n * @return this\n */\n update: function (data) {\n if (typeof data === \"string\") {\n data = sjcl.codec.utf8String.toBits(data);\n }\n var i, b = this._buffer = sjcl.bitArray.concat(this._buffer, data), ol = this._length, nl = this._length = ol + sjcl.bitArray.bitLength(data);\n if (nl > 9007199254740991) {\n throw new sjcl.exception.invalid(\"Cannot hash more than 2^53 - 1 bits\");\n }\n if (typeof Uint32Array !== 'undefined') {\n var c = new Uint32Array(b);\n var j = 0;\n for (i = 512 + ol - ((512 + ol) & 511); i <= nl; i += 512) {\n this._block(c.subarray(16 * j, 16 * (j + 1)));\n j += 1;\n }\n b.splice(0, 16 * j);\n }\n else {\n for (i = 512 + ol - ((512 + ol) & 511); i <= nl; i += 512) {\n this._block(b.splice(0, 16));\n }\n }\n return this;\n },\n /**\n * Complete hashing and output the hash value.\n * @return {bitArray} The hash value, an array of 8 big-endian words.\n */\n finalize: function () {\n var i, b = this._buffer, h = this._h;\n // Round out and push the buffer\n b = sjcl.bitArray.concat(b, [sjcl.bitArray.partial(1, 1)]);\n // Round out the buffer to a multiple of 16 words, less the 2 length words.\n for (i = b.length + 2; i & 15; i++) {\n b.push(0);\n }\n // append the length\n b.push(Math.floor(this._length / 0x100000000));\n b.push(this._length | 0);\n while (b.length) {\n this._block(b.splice(0, 16));\n }\n this.reset();\n return h;\n },\n /**\n * The SHA-256 initialization vector, to be precomputed.\n * @private\n */\n _init: [],\n /*\n _init:[0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19],\n */\n /**\n * The SHA-256 hash key, to be precomputed.\n * @private\n */\n _key: [],\n /*\n _key:\n [0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2],\n */\n /**\n * Function to precompute _init and _key.\n * @private\n */\n _precompute: function () {\n var i = 0, prime = 2, factor, isPrime;\n function frac(x) { return (x - Math.floor(x)) * 0x100000000 | 0; }\n for (; i < 64; prime++) {\n isPrime = true;\n for (factor = 2; factor * factor <= prime; factor++) {\n if (prime % factor === 0) {\n isPrime = false;\n break;\n }\n }\n if (isPrime) {\n if (i < 8) {\n this._init[i] = frac(Math.pow(prime, 1 / 2));\n }\n this._key[i] = frac(Math.pow(prime, 1 / 3));\n i++;\n }\n }\n },\n /**\n * Perform one cycle of SHA-256.\n * @param {Uint32Array|bitArray} w one block of words.\n * @private\n */\n _block: function (w) {\n var i, tmp, a, b, h = this._h, k = this._key, h0 = h[0], h1 = h[1], h2 = h[2], h3 = h[3], h4 = h[4], h5 = h[5], h6 = h[6], h7 = h[7];\n /* Rationale for placement of |0 :\n * If a value can overflow is original 32 bits by a factor of more than a few\n * million (2^23 ish), there is a possibility that it might overflow the\n * 53-bit mantissa and lose precision.\n *\n * To avoid this, we clamp back to 32 bits by |'ing with 0 on any value that\n * propagates around the loop, and on the hash state h[]. I don't believe\n * that the clamps on h4 and on h0 are strictly necessary, but it's close\n * (for h4 anyway), and better safe than sorry.\n *\n * The clamps on h[] are necessary for the output to be correct even in the\n * common case and for short inputs.\n */\n for (i = 0; i < 64; i++) {\n // load up the input word for this round\n if (i < 16) {\n tmp = w[i];\n }\n else {\n a = w[(i + 1) & 15];\n b = w[(i + 14) & 15];\n tmp = w[i & 15] = ((a >>> 7 ^ a >>> 18 ^ a >>> 3 ^ a << 25 ^ a << 14) +\n (b >>> 17 ^ b >>> 19 ^ b >>> 10 ^ b << 15 ^ b << 13) +\n w[i & 15] + w[(i + 9) & 15]) | 0;\n }\n tmp = (tmp + h7 + (h4 >>> 6 ^ h4 >>> 11 ^ h4 >>> 25 ^ h4 << 26 ^ h4 << 21 ^ h4 << 7) + (h6 ^ h4 & (h5 ^ h6)) + k[i]); // | 0;\n // shift register\n h7 = h6;\n h6 = h5;\n h5 = h4;\n h4 = h3 + tmp | 0;\n h3 = h2;\n h2 = h1;\n h1 = h0;\n h0 = (tmp + ((h1 & h2) ^ (h3 & (h1 ^ h2))) + (h1 >>> 2 ^ h1 >>> 13 ^ h1 >>> 22 ^ h1 << 30 ^ h1 << 19 ^ h1 << 10)) | 0;\n }\n h[0] = h[0] + h0 | 0;\n h[1] = h[1] + h1 | 0;\n h[2] = h[2] + h2 | 0;\n h[3] = h[3] + h3 | 0;\n h[4] = h[4] + h4 | 0;\n h[5] = h[5] + h5 | 0;\n h[6] = h[6] + h6 | 0;\n h[7] = h[7] + h7 | 0;\n }\n};\n/** @fileOverview CCM mode implementation.\n *\n * Special thanks to Roy Nicholson for pointing out a bug in our\n * implementation.\n *\n * @author Emily Stark\n * @author Mike Hamburg\n * @author Dan Boneh\n */\n/**\n * CTR mode with CBC MAC.\n * @namespace\n */\nsjcl.mode.ccm = {\n /** The name of the mode.\n * @constant\n */\n name: \"ccm\",\n _progressListeners: [],\n listenProgress: function (cb) {\n sjcl.mode.ccm._progressListeners.push(cb);\n },\n unListenProgress: function (cb) {\n var index = sjcl.mode.ccm._progressListeners.indexOf(cb);\n if (index > -1) {\n sjcl.mode.ccm._progressListeners.splice(index, 1);\n }\n },\n _callProgressListener: function (val) {\n var p = sjcl.mode.ccm._progressListeners.slice(), i;\n for (i = 0; i < p.length; i += 1) {\n p[i](val);\n }\n },\n /** Encrypt in CCM mode.\n * @static\n * @param {Object} prf The pseudorandom function. It must have a block size of 16 bytes.\n * @param {bitArray} plaintext The plaintext data.\n * @param {bitArray} iv The initialization value.\n * @param {bitArray} [adata=[]] The authenticated data.\n * @param {Number} [tlen=64] the desired tag length, in bits.\n * @return {bitArray} The encrypted data, an array of bytes.\n */\n encrypt: function (prf, plaintext, iv, adata, tlen) {\n var L, out = plaintext.slice(0), tag, w = sjcl.bitArray, ivl = w.bitLength(iv) / 8, ol = w.bitLength(out) / 8;\n tlen = tlen || 64;\n adata = adata || [];\n if (ivl < 7) {\n throw new sjcl.exception.invalid(\"ccm: iv must be at least 7 bytes\");\n }\n // compute the length of the length\n for (L = 2; L < 4 && ol >>> 8 * L; L++) { }\n if (L < 15 - ivl) {\n L = 15 - ivl;\n }\n iv = w.clamp(iv, 8 * (15 - L));\n // compute the tag\n tag = sjcl.mode.ccm._computeTag(prf, plaintext, iv, adata, tlen, L);\n // encrypt\n out = sjcl.mode.ccm._ctrMode(prf, out, iv, tag, tlen, L);\n return w.concat(out.data, out.tag);\n },\n /** Decrypt in CCM mode.\n * @static\n * @param {Object} prf The pseudorandom function. It must have a block size of 16 bytes.\n * @param {bitArray} ciphertext The ciphertext data.\n * @param {bitArray} iv The initialization value.\n * @param {bitArray} [adata=[]] adata The authenticated data.\n * @param {Number} [tlen=64] tlen the desired tag length, in bits.\n * @return {bitArray} The decrypted data.\n */\n decrypt: function (prf, ciphertext, iv, adata, tlen) {\n tlen = tlen || 64;\n adata = adata || [];\n var L, w = sjcl.bitArray, ivl = w.bitLength(iv) / 8, ol = w.bitLength(ciphertext), out = w.clamp(ciphertext, ol - tlen), tag = w.bitSlice(ciphertext, ol - tlen), tag2;\n ol = (ol - tlen) / 8;\n if (ivl < 7) {\n throw new sjcl.exception.invalid(\"ccm: iv must be at least 7 bytes\");\n }\n // compute the length of the length\n for (L = 2; L < 4 && ol >>> 8 * L; L++) { }\n if (L < 15 - ivl) {\n L = 15 - ivl;\n }\n iv = w.clamp(iv, 8 * (15 - L));\n // decrypt\n out = sjcl.mode.ccm._ctrMode(prf, out, iv, tag, tlen, L);\n // check the tag\n tag2 = sjcl.mode.ccm._computeTag(prf, out.data, iv, adata, tlen, L);\n if (!w.equal(out.tag, tag2)) {\n throw new sjcl.exception.corrupt(\"ccm: tag doesn't match\");\n }\n return out.data;\n },\n _macAdditionalData: function (prf, adata, iv, tlen, ol, L) {\n var mac, tmp, i, macData = [], w = sjcl.bitArray, xor = w._xor4;\n // mac the flags\n mac = [w.partial(8, (adata.length ? 1 << 6 : 0) | (tlen - 2) << 2 | L - 1)];\n // mac the iv and length\n mac = w.concat(mac, iv);\n mac[3] |= ol;\n mac = prf.encrypt(mac);\n if (adata.length) {\n // mac the associated data. start with its length...\n tmp = w.bitLength(adata) / 8;\n if (tmp <= 0xFEFF) {\n macData = [w.partial(16, tmp)];\n }\n else if (tmp <= 0xFFFFFFFF) {\n macData = w.concat([w.partial(16, 0xFFFE)], [tmp]);\n } // else ...\n // mac the data itself\n macData = w.concat(macData, adata);\n for (i = 0; i < macData.length; i += 4) {\n mac = prf.encrypt(xor(mac, macData.slice(i, i + 4).concat([0, 0, 0])));\n }\n }\n return mac;\n },\n /* Compute the (unencrypted) authentication tag, according to the CCM specification\n * @param {Object} prf The pseudorandom function.\n * @param {bitArray} plaintext The plaintext data.\n * @param {bitArray} iv The initialization value.\n * @param {bitArray} adata The authenticated data.\n * @param {Number} tlen the desired tag length, in bits.\n * @return {bitArray} The tag, but not yet encrypted.\n * @private\n */\n _computeTag: function (prf, plaintext, iv, adata, tlen, L) {\n // compute B[0]\n var mac, i, w = sjcl.bitArray, xor = w._xor4;\n tlen /= 8;\n // check tag length and message length\n if (tlen % 2 || tlen < 4 || tlen > 16) {\n throw new sjcl.exception.invalid(\"ccm: invalid tag length\");\n }\n if (adata.length > 0xFFFFFFFF || plaintext.length > 0xFFFFFFFF) {\n // I don't want to deal with extracting high words from doubles.\n throw new sjcl.exception.bug(\"ccm: can't deal with 4GiB or more data\");\n }\n mac = sjcl.mode.ccm._macAdditionalData(prf, adata, iv, tlen, w.bitLength(plaintext) / 8, L);\n // mac the plaintext\n for (i = 0; i < plaintext.length; i += 4) {\n mac = prf.encrypt(xor(mac, plaintext.slice(i, i + 4).concat([0, 0, 0])));\n }\n return w.clamp(mac, tlen * 8);\n },\n /** CCM CTR mode.\n * Encrypt or decrypt data and tag with the prf in CCM-style CTR mode.\n * May mutate its arguments.\n * @param {Object} prf The PRF.\n * @param {bitArray} data The data to be encrypted or decrypted.\n * @param {bitArray} iv The initialization vector.\n * @param {bitArray} tag The authentication tag.\n * @param {Number} tlen The length of th etag, in bits.\n * @param {Number} L The CCM L value.\n * @return {Object} An object with data and tag, the en/decryption of data and tag values.\n * @private\n */\n _ctrMode: function (prf, data, iv, tag, tlen, L) {\n var enc, i, w = sjcl.bitArray, xor = w._xor4, ctr, l = data.length, bl = w.bitLength(data), n = l / 50, p = n;\n // start the ctr\n ctr = w.concat([w.partial(8, L - 1)], iv).concat([0, 0, 0]).slice(0, 4);\n // en/decrypt the tag\n tag = w.bitSlice(xor(tag, prf.encrypt(ctr)), 0, tlen);\n // en/decrypt the data\n if (!l) {\n return { tag: tag, data: [] };\n }\n for (i = 0; i < l; i += 4) {\n if (i > n) {\n sjcl.mode.ccm._callProgressListener(i / l);\n n += p;\n }\n ctr[3]++;\n enc = prf.encrypt(ctr);\n data[i] ^= enc[0];\n data[i + 1] ^= enc[1];\n data[i + 2] ^= enc[2];\n data[i + 3] ^= enc[3];\n }\n return { tag: tag, data: w.clamp(data, bl) };\n }\n};\n/** @fileOverview HMAC implementation.\n *\n * @author Emily Stark\n * @author Mike Hamburg\n * @author Dan Boneh\n */\n/** HMAC with the specified hash function.\n * @constructor\n * @param {bitArray} key the key for HMAC.\n * @param {Object} [Hash=sjcl.hash.sha256] The hash function to use.\n */\nsjcl.misc.hmac = function (key, Hash) {\n this._hash = Hash = Hash || sjcl.hash.sha256;\n var exKey = [[], []], i, bs = Hash.prototype.blockSize / 32;\n this._baseHash = [new Hash(), new Hash()];\n if (key.length > bs) {\n key = Hash.hash(key);\n }\n for (i = 0; i < bs; i++) {\n exKey[0][i] = key[i] ^ 0x36363636;\n exKey[1][i] = key[i] ^ 0x5C5C5C5C;\n }\n this._baseHash[0].update(exKey[0]);\n this._baseHash[1].update(exKey[1]);\n this._resultHash = new Hash(this._baseHash[0]);\n};\n/** HMAC with the specified hash function. Also called encrypt since it's a prf.\n * @param {bitArray|String} data The data to mac.\n */\nsjcl.misc.hmac.prototype.encrypt = sjcl.misc.hmac.prototype.mac = function (data) {\n if (!this._updated) {\n this.update(data);\n return this.digest(data);\n }\n else {\n throw new sjcl.exception.invalid(\"encrypt on already updated hmac called!\");\n }\n};\nsjcl.misc.hmac.prototype.reset = function () {\n this._resultHash = new this._hash(this._baseHash[0]);\n this._updated = false;\n};\nsjcl.misc.hmac.prototype.update = function (data) {\n this._updated = true;\n this._resultHash.update(data);\n};\nsjcl.misc.hmac.prototype.digest = function () {\n var w = this._resultHash.finalize(), result = new (this._hash)(this._baseHash[1]).update(w).finalize();\n this.reset();\n return result;\n};\n/** @fileOverview Password-based key-derivation function, version 2.0.\n *\n * @author Emily Stark\n * @author Mike Hamburg\n * @author Dan Boneh\n */\n/** Password-Based Key-Derivation Function, version 2.0.\n *\n * Generate keys from passwords using PBKDF2-HMAC-SHA256.\n *\n * This is the method specified by RSA's PKCS #5 standard.\n *\n * @param {bitArray|String} password The password.\n * @param {bitArray|String} salt The salt. Should have lots of entropy.\n * @param {Number} [count=1000] The number of iterations. Higher numbers make the function slower but more secure.\n * @param {Number} [length] The length of the derived key. Defaults to the\n output size of the hash function.\n * @param {Object} [Prff=sjcl.misc.hmac] The pseudorandom function family.\n * @return {bitArray} the derived key.\n */\nsjcl.misc.pbkdf2 = function (password, salt, count, length, Prff) {\n count = count || 10000;\n if (length < 0 || count < 0) {\n throw new sjcl.exception.invalid(\"invalid params to pbkdf2\");\n }\n if (typeof password === \"string\") {\n password = sjcl.codec.utf8String.toBits(password);\n }\n if (typeof salt === \"string\") {\n salt = sjcl.codec.utf8String.toBits(salt);\n }\n Prff = Prff || sjcl.misc.hmac;\n var prf = new Prff(password), u, ui, i, j, k, out = [], b = sjcl.bitArray;\n for (k = 1; 32 * out.length < (length || 1); k++) {\n u = ui = prf.encrypt(b.concat(salt, [k]));\n for (i = 1; i < count; i++) {\n ui = prf.encrypt(ui);\n for (j = 0; j < ui.length; j++) {\n u[j] ^= ui[j];\n }\n }\n out = out.concat(u);\n }\n if (length) {\n out = b.clamp(out, length);\n }\n return out;\n};\n/** @fileOverview Random number generator.\n *\n * @author Emily Stark\n * @author Mike Hamburg\n * @author Dan Boneh\n * @author Michael Brooks\n * @author Steve Thomas\n */\n/**\n * @class Random number generator\n * @description\n * Use sjcl.random as a singleton for this class!\n *\n * This random number generator is a derivative of Ferguson and Schneier's\n * generator Fortuna. It collects entropy from various events into several\n * pools, implemented by streaming SHA-256 instances. It differs from\n * ordinary Fortuna in a few ways, though.\n *
\n *\n *\n * Most importantly, it has an entropy estimator. This is present because\n * there is a strong conflict here between making the generator available\n * as soon as possible, and making sure that it doesn't \"run on empty\".\n * In Fortuna, there is a saved state file, and the system is likely to have\n * time to warm up.\n *
\n *\n *\n * Second, because users are unlikely to stay on the page for very long,\n * and to speed startup time, the number of pools increases logarithmically:\n * a new pool is created when the previous one is actually used for a reseed.\n * This gives the same asymptotic guarantees as Fortuna, but gives more\n * entropy to early reseeds.\n *
\n *\n *\n * The entire mechanism here feels pretty klunky. Furthermore, there are\n * several improvements that should be made, including support for\n * dedicated cryptographic functions that may be present in some browsers;\n * state files in local storage; cookies containing randomness; etc. So\n * look for improvements in future versions.\n *
\n * @constructor\n */\nsjcl.prng = function (defaultParanoia) {\n /* private */\n this._pools = [new sjcl.hash.sha256()];\n this._poolEntropy = [0];\n this._reseedCount = 0;\n this._robins = {};\n this._eventId = 0;\n this._collectorIds = {};\n this._collectorIdNext = 0;\n this._strength = 0;\n this._poolStrength = 0;\n this._nextReseed = 0;\n this._key = [0, 0, 0, 0, 0, 0, 0, 0];\n this._counter = [0, 0, 0, 0];\n this._cipher = undefined;\n this._defaultParanoia = defaultParanoia;\n /* event listener stuff */\n this._collectorsStarted = false;\n this._callbacks = { progress: {}, seeded: {} };\n this._callbackI = 0;\n /* constants */\n this._NOT_READY = 0;\n this._READY = 1;\n this._REQUIRES_RESEED = 2;\n this._MAX_WORDS_PER_BURST = 65536;\n this._PARANOIA_LEVELS = [0, 48, 64, 96, 128, 192, 256, 384, 512, 768, 1024];\n this._MILLISECONDS_PER_RESEED = 30000;\n this._BITS_PER_RESEED = 80;\n};\nsjcl.prng.prototype = {\n /** Generate several random words, and return them in an array.\n * A word consists of 32 bits (4 bytes)\n * @param {Number} nwords The number of words to generate.\n */\n randomWords: function (nwords, paranoia) {\n var out = [], i, readiness = this.isReady(paranoia), g;\n if (readiness === this._NOT_READY) {\n throw new sjcl.exception.notReady(\"generator isn't seeded\");\n }\n else if (readiness & this._REQUIRES_RESEED) {\n this._reseedFromPools(!(readiness & this._READY));\n }\n for (i = 0; i < nwords; i += 4) {\n if ((i + 1) % this._MAX_WORDS_PER_BURST === 0) {\n this._gate();\n }\n g = this._gen4words();\n out.push(g[0], g[1], g[2], g[3]);\n }\n this._gate();\n return out.slice(0, nwords);\n },\n setDefaultParanoia: function (paranoia, allowZeroParanoia) {\n if (paranoia === 0 && allowZeroParanoia !== \"Setting paranoia=0 will ruin your security; use it only for testing\") {\n throw new sjcl.exception.invalid(\"Setting paranoia=0 will ruin your security; use it only for testing\");\n }\n this._defaultParanoia = paranoia;\n },\n /**\n * Add entropy to the pools.\n * @param data The entropic value. Should be a 32-bit integer, array of 32-bit integers, or string\n * @param {Number} estimatedEntropy The estimated entropy of data, in bits\n * @param {String} source The source of the entropy, eg \"mouse\"\n */\n addEntropy: function (data, estimatedEntropy, source) {\n source = source || \"user\";\n var id, i, tmp, t = (new Date()).valueOf(), robin = this._robins[source], oldReady = this.isReady(), err = 0, objName;\n id = this._collectorIds[source];\n if (id === undefined) {\n id = this._collectorIds[source] = this._collectorIdNext++;\n }\n if (robin === undefined) {\n robin = this._robins[source] = 0;\n }\n this._robins[source] = (this._robins[source] + 1) % this._pools.length;\n switch (typeof (data)) {\n case \"number\":\n if (estimatedEntropy === undefined) {\n estimatedEntropy = 1;\n }\n this._pools[robin].update([id, this._eventId++, 1, estimatedEntropy, t, 1, data | 0]);\n break;\n case \"object\":\n objName = Object.prototype.toString.call(data);\n if (objName === \"[object Uint32Array]\") {\n tmp = [];\n for (i = 0; i < data.length; i++) {\n tmp.push(data[i]);\n }\n data = tmp;\n }\n else {\n if (objName !== \"[object Array]\") {\n err = 1;\n }\n for (i = 0; i < data.length && !err; i++) {\n if (typeof (data[i]) !== \"number\") {\n err = 1;\n }\n }\n }\n if (!err) {\n if (estimatedEntropy === undefined) {\n /* horrible entropy estimator */\n estimatedEntropy = 0;\n for (i = 0; i < data.length; i++) {\n tmp = data[i];\n while (tmp > 0) {\n estimatedEntropy++;\n tmp = tmp >>> 1;\n }\n }\n }\n this._pools[robin].update([id, this._eventId++, 2, estimatedEntropy, t, data.length].concat(data));\n }\n break;\n case \"string\":\n if (estimatedEntropy === undefined) {\n /* English text has just over 1 bit per character of entropy.\n * But this might be HTML or something, and have far less\n * entropy than English... Oh well, let's just say one bit.\n */\n estimatedEntropy = data.length;\n }\n this._pools[robin].update([id, this._eventId++, 3, estimatedEntropy, t, data.length]);\n this._pools[robin].update(data);\n break;\n default:\n err = 1;\n }\n if (err) {\n throw new sjcl.exception.bug(\"random: addEntropy only supports number, array of numbers or string\");\n }\n /* record the new strength */\n this._poolEntropy[robin] += estimatedEntropy;\n this._poolStrength += estimatedEntropy;\n /* fire off events */\n if (oldReady === this._NOT_READY) {\n if (this.isReady() !== this._NOT_READY) {\n this._fireEvent(\"seeded\", Math.max(this._strength, this._poolStrength));\n }\n this._fireEvent(\"progress\", this.getProgress());\n }\n },\n /** Is the generator ready? */\n isReady: function (paranoia) {\n var entropyRequired = this._PARANOIA_LEVELS[(paranoia !== undefined) ? paranoia : this._defaultParanoia];\n if (this._strength && this._strength >= entropyRequired) {\n return (this._poolEntropy[0] > this._BITS_PER_RESEED && (new Date()).valueOf() > this._nextReseed) ?\n this._REQUIRES_RESEED | this._READY :\n this._READY;\n }\n else {\n return (this._poolStrength >= entropyRequired) ?\n this._REQUIRES_RESEED | this._NOT_READY :\n this._NOT_READY;\n }\n },\n /** Get the generator's progress toward readiness, as a fraction */\n getProgress: function (paranoia) {\n var entropyRequired = this._PARANOIA_LEVELS[paranoia ? paranoia : this._defaultParanoia];\n if (this._strength >= entropyRequired) {\n return 1.0;\n }\n else {\n return (this._poolStrength > entropyRequired) ?\n 1.0 :\n this._poolStrength / entropyRequired;\n }\n },\n /** start the built-in entropy collectors */\n startCollectors: function () {\n if (this._collectorsStarted) {\n return;\n }\n this._eventListener = {\n loadTimeCollector: this._bind(this._loadTimeCollector),\n mouseCollector: this._bind(this._mouseCollector),\n keyboardCollector: this._bind(this._keyboardCollector),\n accelerometerCollector: this._bind(this._accelerometerCollector),\n touchCollector: this._bind(this._touchCollector)\n };\n if (window.addEventListener) {\n window.addEventListener(\"load\", this._eventListener.loadTimeCollector, false);\n window.addEventListener(\"mousemove\", this._eventListener.mouseCollector, false);\n window.addEventListener(\"keypress\", this._eventListener.keyboardCollector, false);\n window.addEventListener(\"devicemotion\", this._eventListener.accelerometerCollector, false);\n window.addEventListener(\"touchmove\", this._eventListener.touchCollector, false);\n }\n else if (document.attachEvent) {\n document.attachEvent(\"onload\", this._eventListener.loadTimeCollector);\n document.attachEvent(\"onmousemove\", this._eventListener.mouseCollector);\n document.attachEvent(\"keypress\", this._eventListener.keyboardCollector);\n }\n else {\n throw new sjcl.exception.bug(\"can't attach event\");\n }\n this._collectorsStarted = true;\n },\n /** stop the built-in entropy collectors */\n stopCollectors: function () {\n if (!this._collectorsStarted) {\n return;\n }\n if (window.removeEventListener) {\n window.removeEventListener(\"load\", this._eventListener.loadTimeCollector, false);\n window.removeEventListener(\"mousemove\", this._eventListener.mouseCollector, false);\n window.removeEventListener(\"keypress\", this._eventListener.keyboardCollector, false);\n window.removeEventListener(\"devicemotion\", this._eventListener.accelerometerCollector, false);\n window.removeEventListener(\"touchmove\", this._eventListener.touchCollector, false);\n }\n else if (document.detachEvent) {\n document.detachEvent(\"onload\", this._eventListener.loadTimeCollector);\n document.detachEvent(\"onmousemove\", this._eventListener.mouseCollector);\n document.detachEvent(\"keypress\", this._eventListener.keyboardCollector);\n }\n this._collectorsStarted = false;\n },\n /* use a cookie to store entropy.\n useCookie: function (all_cookies) {\n throw new sjcl.exception.bug(\"random: useCookie is unimplemented\");\n },*/\n /** add an event listener for progress or seeded-ness. */\n addEventListener: function (name, callback) {\n this._callbacks[name][this._callbackI++] = callback;\n },\n /** remove an event listener for progress or seeded-ness */\n removeEventListener: function (name, cb) {\n var i, j, cbs = this._callbacks[name], jsTemp = [];\n /* I'm not sure if this is necessary; in C++, iterating over a\n * collection and modifying it at the same time is a no-no.\n */\n for (j in cbs) {\n if (cbs.hasOwnProperty(j) && cbs[j] === cb) {\n jsTemp.push(j);\n }\n }\n for (i = 0; i < jsTemp.length; i++) {\n j = jsTemp[i];\n delete cbs[j];\n }\n },\n _bind: function (func) {\n var that = this;\n return function () {\n func.apply(that, arguments);\n };\n },\n /** Generate 4 random words, no reseed, no gate.\n * @private\n */\n _gen4words: function () {\n for (var i = 0; i < 4; i++) {\n this._counter[i] = this._counter[i] + 1 | 0;\n if (this._counter[i]) {\n break;\n }\n }\n return this._cipher.encrypt(this._counter);\n },\n /* Rekey the AES instance with itself after a request, or every _MAX_WORDS_PER_BURST words.\n * @private\n */\n _gate: function () {\n this._key = this._gen4words().concat(this._gen4words());\n this._cipher = new sjcl.cipher.aes(this._key);\n },\n /** Reseed the generator with the given words\n * @private\n */\n _reseed: function (seedWords) {\n this._key = sjcl.hash.sha256.hash(this._key.concat(seedWords));\n this._cipher = new sjcl.cipher.aes(this._key);\n for (var i = 0; i < 4; i++) {\n this._counter[i] = this._counter[i] + 1 | 0;\n if (this._counter[i]) {\n break;\n }\n }\n },\n /** reseed the data from the entropy pools\n * @param full If set, use all the entropy pools in the reseed.\n */\n _reseedFromPools: function (full) {\n var reseedData = [], strength = 0, i;\n this._nextReseed = reseedData[0] =\n (new Date()).valueOf() + this._MILLISECONDS_PER_RESEED;\n for (i = 0; i < 16; i++) {\n /* On some browsers, this is cryptographically random. So we might\n * as well toss it in the pot and stir...\n */\n reseedData.push(Math.random() * 0x100000000 | 0);\n }\n for (i = 0; i < this._pools.length; i++) {\n reseedData = reseedData.concat(this._pools[i].finalize());\n strength += this._poolEntropy[i];\n this._poolEntropy[i] = 0;\n if (!full && (this._reseedCount & (1 << i))) {\n break;\n }\n }\n /* if we used the last pool, push a new one onto the stack */\n if (this._reseedCount >= 1 << this._pools.length) {\n this._pools.push(new sjcl.hash.sha256());\n this._poolEntropy.push(0);\n }\n /* how strong was this reseed? */\n this._poolStrength -= strength;\n if (strength > this._strength) {\n this._strength = strength;\n }\n this._reseedCount++;\n this._reseed(reseedData);\n },\n _keyboardCollector: function () {\n this._addCurrentTimeToEntropy(1);\n },\n _mouseCollector: function (ev) {\n var x, y;\n try {\n x = ev.x || ev.clientX || ev.offsetX || 0;\n y = ev.y || ev.clientY || ev.offsetY || 0;\n }\n catch (err) {\n // Event originated from a secure element. No mouse position available.\n x = 0;\n y = 0;\n }\n if (x != 0 && y != 0) {\n this.addEntropy([x, y], 2, \"mouse\");\n }\n this._addCurrentTimeToEntropy(0);\n },\n _touchCollector: function (ev) {\n var touch = ev.touches[0] || ev.changedTouches[0];\n var x = touch.pageX || touch.clientX, y = touch.pageY || touch.clientY;\n this.addEntropy([x, y], 1, \"touch\");\n this._addCurrentTimeToEntropy(0);\n },\n _loadTimeCollector: function () {\n this._addCurrentTimeToEntropy(2);\n },\n _addCurrentTimeToEntropy: function (estimatedEntropy) {\n if (typeof window !== 'undefined' && window.performance && typeof window.performance.now === \"function\") {\n //how much entropy do we want to add here?\n this.addEntropy(window.performance.now(), estimatedEntropy, \"loadtime\");\n }\n else {\n this.addEntropy((new Date()).valueOf(), estimatedEntropy, \"loadtime\");\n }\n },\n _accelerometerCollector: function (ev) {\n var ac = ev.accelerationIncludingGravity.x || ev.accelerationIncludingGravity.y || ev.accelerationIncludingGravity.z;\n if (window.orientation) {\n var or = window.orientation;\n if (typeof or === \"number\") {\n this.addEntropy(or, 1, \"accelerometer\");\n }\n }\n if (ac) {\n this.addEntropy(ac, 2, \"accelerometer\");\n }\n this._addCurrentTimeToEntropy(0);\n },\n _fireEvent: function (name, arg) {\n var j, cbs = sjcl.random._callbacks[name], cbsTemp = [];\n /* TODO: there is a race condition between removing collectors and firing them */\n /* I'm not sure if this is necessary; in C++, iterating over a\n * collection and modifying it at the same time is a no-no.\n */\n for (j in cbs) {\n if (cbs.hasOwnProperty(j)) {\n cbsTemp.push(cbs[j]);\n }\n }\n for (j = 0; j < cbsTemp.length; j++) {\n cbsTemp[j](arg);\n }\n }\n};\n/** an instance for the prng.\n* @see sjcl.prng\n*/\nsjcl.random = new sjcl.prng(6);\n(function () {\n // function for getting nodejs crypto module. catches and ignores errors.\n function getCryptoModule() {\n try {\n return require('crypto');\n }\n catch (e) {\n return null;\n }\n }\n try {\n var buf, crypt, ab;\n // get cryptographically strong entropy depending on runtime environment\n if (typeof module !== 'undefined' && module.exports && (crypt = getCryptoModule()) && crypt.randomBytes) {\n buf = crypt.randomBytes(1024 / 8);\n buf = new Uint32Array(new Uint8Array(buf).buffer);\n sjcl.random.addEntropy(buf, 1024, \"crypto.randomBytes\");\n }\n else if (typeof window !== 'undefined' && typeof Uint32Array !== 'undefined') {\n ab = new Uint32Array(32);\n if (window.crypto && window.crypto.getRandomValues) {\n window.crypto.getRandomValues(ab);\n }\n else if (window.msCrypto && window.msCrypto.getRandomValues) {\n window.msCrypto.getRandomValues(ab);\n }\n else {\n return;\n }\n // get cryptographically strong entropy in Webkit\n sjcl.random.addEntropy(ab, 1024, \"crypto.getRandomValues\");\n }\n else {\n // no getRandomValues :-(\n }\n }\n catch (e) {\n if (typeof window !== 'undefined' && window.console) {\n console.log(\"There was an error collecting entropy from the browser:\");\n console.log(e);\n //we do not want the library to fail due to randomness not being maintained.\n }\n }\n}());\n/** @fileOverview Convenience functions centered around JSON encapsulation.\n *\n * @author Emily Stark\n * @author Mike Hamburg\n * @author Dan Boneh\n */\n/**\n * JSON encapsulation\n * @namespace\n */\nsjcl.json = {\n /** Default values for encryption */\n defaults: { v: 1, iter: 10000, ks: 128, ts: 64, mode: \"ccm\", adata: \"\", cipher: \"aes\" },\n /** Simple encryption function.\n * @param {String|bitArray} password The password or key.\n * @param {String} plaintext The data to encrypt.\n * @param {Object} [params] The parameters including tag, iv and salt.\n * @param {Object} [rp] A returned version with filled-in parameters.\n * @return {Object} The cipher raw data.\n * @throws {sjcl.exception.invalid} if a parameter is invalid.\n */\n _encrypt: function (password, plaintext, params, rp) {\n params = params || {};\n rp = rp || {};\n var j = sjcl.json, p = j._add({ iv: sjcl.random.randomWords(4, 0) }, j.defaults), tmp, prp, adata;\n j._add(p, params);\n adata = p.adata;\n if (typeof p.salt === \"string\") {\n p.salt = sjcl.codec.base64.toBits(p.salt);\n }\n if (typeof p.iv === \"string\") {\n p.iv = sjcl.codec.base64.toBits(p.iv);\n }\n if (!sjcl.mode[p.mode] ||\n !sjcl.cipher[p.cipher] ||\n (typeof password === \"string\" && p.iter <= 100) ||\n (p.ts !== 64 && p.ts !== 96 && p.ts !== 128) ||\n (p.ks !== 128 && p.ks !== 192 && p.ks !== 256) ||\n (p.iv.length < 2 || p.iv.length > 4)) {\n throw new sjcl.exception.invalid(\"json encrypt: invalid parameters\");\n }\n if (typeof password === \"string\") {\n tmp = sjcl.misc.cachedPbkdf2(password, p);\n password = tmp.key.slice(0, p.ks / 32);\n p.salt = tmp.salt;\n }\n else if (sjcl.ecc && password instanceof sjcl.ecc.elGamal.publicKey) {\n tmp = password.kem();\n p.kemtag = tmp.tag;\n password = tmp.key.slice(0, p.ks / 32);\n }\n if (typeof plaintext === \"string\") {\n plaintext = sjcl.codec.utf8String.toBits(plaintext);\n }\n if (typeof adata === \"string\") {\n p.adata = adata = sjcl.codec.utf8String.toBits(adata);\n }\n prp = new sjcl.cipher[p.cipher](password);\n /* return the json data */\n j._add(rp, p);\n rp.key = password;\n /* do the encryption */\n if (p.mode === \"ccm\" && sjcl.arrayBuffer && sjcl.arrayBuffer.ccm && plaintext instanceof ArrayBuffer) {\n p.ct = sjcl.arrayBuffer.ccm.encrypt(prp, plaintext, p.iv, adata, p.ts);\n }\n else {\n p.ct = sjcl.mode[p.mode].encrypt(prp, plaintext, p.iv, adata, p.ts);\n }\n //return j.encode(j._subtract(p, j.defaults));\n return p;\n },\n /** Simple encryption function.\n * @param {String|bitArray} password The password or key.\n * @param {String} plaintext The data to encrypt.\n * @param {Object} [params] The parameters including tag, iv and salt.\n * @param {Object} [rp] A returned version with filled-in parameters.\n * @return {String} The ciphertext serialized data.\n * @throws {sjcl.exception.invalid} if a parameter is invalid.\n */\n encrypt: function (password, plaintext, params, rp) {\n var j = sjcl.json, p = j._encrypt.apply(j, arguments);\n return j.encode(p);\n },\n /** Simple decryption function.\n * @param {String|bitArray} password The password or key.\n * @param {Object} ciphertext The cipher raw data to decrypt.\n * @param {Object} [params] Additional non-default parameters.\n * @param {Object} [rp] A returned object with filled parameters.\n * @return {String} The plaintext.\n * @throws {sjcl.exception.invalid} if a parameter is invalid.\n * @throws {sjcl.exception.corrupt} if the ciphertext is corrupt.\n */\n _decrypt: function (password, ciphertext, params, rp) {\n params = params || {};\n rp = rp || {};\n var j = sjcl.json, p = j._add(j._add(j._add({}, j.defaults), ciphertext), params, true), ct, tmp, prp, adata = p.adata;\n if (typeof p.salt === \"string\") {\n p.salt = sjcl.codec.base64.toBits(p.salt);\n }\n if (typeof p.iv === \"string\") {\n p.iv = sjcl.codec.base64.toBits(p.iv);\n }\n if (!sjcl.mode[p.mode] ||\n !sjcl.cipher[p.cipher] ||\n (typeof password === \"string\" && p.iter <= 100) ||\n (p.ts !== 64 && p.ts !== 96 && p.ts !== 128) ||\n (p.ks !== 128 && p.ks !== 192 && p.ks !== 256) ||\n (!p.iv) ||\n (p.iv.length < 2 || p.iv.length > 4)) {\n throw new sjcl.exception.invalid(\"json decrypt: invalid parameters\");\n }\n if (typeof password === \"string\") {\n tmp = sjcl.misc.cachedPbkdf2(password, p);\n password = tmp.key.slice(0, p.ks / 32);\n p.salt = tmp.salt;\n }\n else if (sjcl.ecc && password instanceof sjcl.ecc.elGamal.secretKey) {\n password = password.unkem(sjcl.codec.base64.toBits(p.kemtag)).slice(0, p.ks / 32);\n }\n if (typeof adata === \"string\") {\n adata = sjcl.codec.utf8String.toBits(adata);\n }\n prp = new sjcl.cipher[p.cipher](password);\n /* do the decryption */\n if (p.mode === \"ccm\" && sjcl.arrayBuffer && sjcl.arrayBuffer.ccm && p.ct instanceof ArrayBuffer) {\n ct = sjcl.arrayBuffer.ccm.decrypt(prp, p.ct, p.iv, p.tag, adata, p.ts);\n }\n else {\n ct = sjcl.mode[p.mode].decrypt(prp, p.ct, p.iv, adata, p.ts);\n }\n /* return the json data */\n j._add(rp, p);\n rp.key = password;\n if (params.raw === 1) {\n return ct;\n }\n else {\n return sjcl.codec.utf8String.fromBits(ct);\n }\n },\n /** Simple decryption function.\n * @param {String|bitArray} password The password or key.\n * @param {String} ciphertext The ciphertext to decrypt.\n * @param {Object} [params] Additional non-default parameters.\n * @param {Object} [rp] A returned object with filled parameters.\n * @return {String} The plaintext.\n * @throws {sjcl.exception.invalid} if a parameter is invalid.\n * @throws {sjcl.exception.corrupt} if the ciphertext is corrupt.\n */\n decrypt: function (password, ciphertext, params, rp) {\n var j = sjcl.json;\n return j._decrypt(password, j.decode(ciphertext), params, rp);\n },\n /** Encode a flat structure into a JSON string.\n * @param {Object} obj The structure to encode.\n * @return {String} A JSON string.\n * @throws {sjcl.exception.invalid} if obj has a non-alphanumeric property.\n * @throws {sjcl.exception.bug} if a parameter has an unsupported type.\n */\n encode: function (obj) {\n var i, out = '{', comma = '';\n for (i in obj) {\n if (obj.hasOwnProperty(i)) {\n if (!i.match(/^[a-z0-9]+$/i)) {\n throw new sjcl.exception.invalid(\"json encode: invalid property name\");\n }\n out += comma + '\"' + i + '\":';\n comma = ',';\n switch (typeof obj[i]) {\n case 'number':\n case 'boolean':\n out += obj[i];\n break;\n case 'string':\n out += '\"' + escape(obj[i]) + '\"';\n break;\n case 'object':\n out += '\"' + sjcl.codec.base64.fromBits(obj[i], 0) + '\"';\n break;\n default:\n throw new sjcl.exception.bug(\"json encode: unsupported type\");\n }\n }\n }\n return out + '}';\n },\n /** Decode a simple (flat) JSON string into a structure. The ciphertext,\n * adata, salt and iv will be base64-decoded.\n * @param {String} str The string.\n * @return {Object} The decoded structure.\n * @throws {sjcl.exception.invalid} if str isn't (simple) JSON.\n */\n decode: function (str) {\n str = str.replace(/\\s/g, '');\n if (!str.match(/^\\{.*\\}$/)) {\n throw new sjcl.exception.invalid(\"json decode: this isn't json!\");\n }\n var a = str.replace(/^\\{|\\}$/g, '').split(/,/), out = {}, i, m;\n for (i = 0; i < a.length; i++) {\n if (!(m = a[i].match(/^\\s*(?:([\"']?)([a-z][a-z0-9]*)\\1)\\s*:\\s*(?:(-?\\d+)|\"([a-z0-9+\\/%*_.@=\\-]*)\"|(true|false))$/i))) {\n throw new sjcl.exception.invalid(\"json decode: this isn't json!\");\n }\n if (m[3] != null) {\n out[m[2]] = parseInt(m[3], 10);\n }\n else if (m[4] != null) {\n out[m[2]] = m[2].match(/^(ct|adata|salt|iv)$/) ? sjcl.codec.base64.toBits(m[4]) : unescape(m[4]);\n }\n else if (m[5] != null) {\n out[m[2]] = m[5] === 'true';\n }\n }\n return out;\n },\n /** Insert all elements of src into target, modifying and returning target.\n * @param {Object} target The object to be modified.\n * @param {Object} src The object to pull data from.\n * @param {boolean} [requireSame=false] If true, throw an exception if any field of target differs from corresponding field of src.\n * @return {Object} target.\n * @private\n */\n _add: function (target, src, requireSame) {\n if (target === undefined) {\n target = {};\n }\n if (src === undefined) {\n return target;\n }\n var i;\n for (i in src) {\n if (src.hasOwnProperty(i)) {\n if (requireSame && target[i] !== undefined && target[i] !== src[i]) {\n throw new sjcl.exception.invalid(\"required parameter overridden\");\n }\n target[i] = src[i];\n }\n }\n return target;\n },\n /** Remove all elements of minus from plus. Does not modify plus.\n * @private\n */\n _subtract: function (plus, minus) {\n var out = {}, i;\n for (i in plus) {\n if (plus.hasOwnProperty(i) && plus[i] !== minus[i]) {\n out[i] = plus[i];\n }\n }\n return out;\n },\n /** Return only the specified elements of src.\n * @private\n */\n _filter: function (src, filter) {\n var out = {}, i;\n for (i = 0; i < filter.length; i++) {\n if (src[filter[i]] !== undefined) {\n out[filter[i]] = src[filter[i]];\n }\n }\n return out;\n }\n};\n/** Simple encryption function; convenient shorthand for sjcl.json.encrypt.\n * @param {String|bitArray} password The password or key.\n * @param {String} plaintext The data to encrypt.\n * @param {Object} [params] The parameters including tag, iv and salt.\n * @param {Object} [rp] A returned version with filled-in parameters.\n * @return {String} The ciphertext.\n */\nsjcl.encrypt = sjcl.json.encrypt;\n/** Simple decryption function; convenient shorthand for sjcl.json.decrypt.\n * @param {String|bitArray} password The password or key.\n * @param {String} ciphertext The ciphertext to decrypt.\n * @param {Object} [params] Additional non-default parameters.\n * @param {Object} [rp] A returned object with filled parameters.\n * @return {String} The plaintext.\n */\nsjcl.decrypt = sjcl.json.decrypt;\n/** The cache for cachedPbkdf2.\n * @private\n */\nsjcl.misc._pbkdf2Cache = {};\n/** Cached PBKDF2 key derivation.\n * @param {String} password The password.\n * @param {Object} [obj] The derivation params (iteration count and optional salt).\n * @return {Object} The derived data in key, the salt in salt.\n */\nsjcl.misc.cachedPbkdf2 = function (password, obj) {\n var cache = sjcl.misc._pbkdf2Cache, c, cp, str, salt, iter;\n obj = obj || {};\n iter = obj.iter || 1000;\n /* open the cache for this password and iteration count */\n cp = cache[password] = cache[password] || {};\n c = cp[iter] = cp[iter] || { firstSalt: (obj.salt && obj.salt.length) ?\n obj.salt.slice(0) : sjcl.random.randomWords(2, 0) };\n salt = (obj.salt === undefined) ? c.firstSalt : obj.salt;\n c[salt] = c[salt] || sjcl.misc.pbkdf2(password, salt, obj.iter);\n return { key: c[salt].slice(0), salt: salt.slice(0) };\n};\n// Thanks to Colin McRae and Jonathan Burns of ionic security\n// for reporting and fixing two bugs in this file!\n/**\n * Constructs a new bignum from another bignum, a number or a hex string.\n * @constructor\n */\nsjcl.bn = function (it) {\n this.initWith(it);\n};\nsjcl.bn.prototype = {\n radix: 24,\n maxMul: 8,\n _class: sjcl.bn,\n copy: function () {\n return new this._class(this);\n },\n /**\n * Initializes this with it, either as a bn, a number, or a hex string.\n */\n initWith: function (it) {\n var i = 0, k;\n switch (typeof it) {\n case \"object\":\n this.limbs = it.limbs.slice(0);\n break;\n case \"number\":\n this.limbs = [it];\n this.normalize();\n break;\n case \"string\":\n it = it.replace(/^0x/, '');\n this.limbs = [];\n // hack\n k = this.radix / 4;\n for (i = 0; i < it.length; i += k) {\n this.limbs.push(parseInt(it.substring(Math.max(it.length - i - k, 0), it.length - i), 16));\n }\n break;\n default:\n this.limbs = [0];\n }\n return this;\n },\n /**\n * Returns true if \"this\" and \"that\" are equal. Calls fullReduce().\n * Equality test is in constant time.\n */\n equals: function (that) {\n if (typeof that === \"number\") {\n that = new this._class(that);\n }\n var difference = 0, i;\n this.fullReduce();\n that.fullReduce();\n for (i = 0; i < this.limbs.length || i < that.limbs.length; i++) {\n difference |= this.getLimb(i) ^ that.getLimb(i);\n }\n return (difference === 0);\n },\n /**\n * Get the i'th limb of this, zero if i is too large.\n */\n getLimb: function (i) {\n return (i >= this.limbs.length) ? 0 : this.limbs[i];\n },\n /**\n * Constant time comparison function.\n * Returns 1 if this >= that, or zero otherwise.\n */\n greaterEquals: function (that) {\n if (typeof that === \"number\") {\n that = new this._class(that);\n }\n var less = 0, greater = 0, i, a, b;\n i = Math.max(this.limbs.length, that.limbs.length) - 1;\n for (; i >= 0; i--) {\n a = this.getLimb(i);\n b = that.getLimb(i);\n greater |= (b - a) & ~less;\n less |= (a - b) & ~greater;\n }\n return (greater | ~less) >>> 31;\n },\n /**\n * Convert to a hex string.\n */\n toString: function () {\n this.fullReduce();\n var out = \"\", i, s, l = this.limbs;\n for (i = 0; i < this.limbs.length; i++) {\n s = l[i].toString(16);\n while (i < this.limbs.length - 1 && s.length < 6) {\n s = \"0\" + s;\n }\n out = s + out;\n }\n return \"0x\" + out;\n },\n /** this += that. Does not normalize. */\n addM: function (that) {\n if (typeof (that) !== \"object\") {\n that = new this._class(that);\n }\n var i, l = this.limbs, ll = that.limbs;\n for (i = l.length; i < ll.length; i++) {\n l[i] = 0;\n }\n for (i = 0; i < ll.length; i++) {\n l[i] += ll[i];\n }\n return this;\n },\n /** this *= 2. Requires normalized; ends up normalized. */\n doubleM: function () {\n var i, carry = 0, tmp, r = this.radix, m = this.radixMask, l = this.limbs;\n for (i = 0; i < l.length; i++) {\n tmp = l[i];\n tmp = tmp + tmp + carry;\n l[i] = tmp & m;\n carry = tmp >> r;\n }\n if (carry) {\n l.push(carry);\n }\n return this;\n },\n /** this /= 2, rounded down. Requires normalized; ends up normalized. */\n halveM: function () {\n var i, carry = 0, tmp, r = this.radix, l = this.limbs;\n for (i = l.length - 1; i >= 0; i--) {\n tmp = l[i];\n l[i] = (tmp + carry) >> 1;\n carry = (tmp & 1) << r;\n }\n if (!l[l.length - 1]) {\n l.pop();\n }\n return this;\n },\n /** this -= that. Does not normalize. */\n subM: function (that) {\n if (typeof (that) !== \"object\") {\n that = new this._class(that);\n }\n var i, l = this.limbs, ll = that.limbs;\n for (i = l.length; i < ll.length; i++) {\n l[i] = 0;\n }\n for (i = 0; i < ll.length; i++) {\n l[i] -= ll[i];\n }\n return this;\n },\n mod: function (that) {\n var neg = !this.greaterEquals(new sjcl.bn(0));\n that = new sjcl.bn(that).normalize(); // copy before we begin\n var out = new sjcl.bn(this).normalize(), ci = 0;\n if (neg)\n out = (new sjcl.bn(0)).subM(out).normalize();\n for (; out.greaterEquals(that); ci++) {\n that.doubleM();\n }\n if (neg)\n out = that.sub(out).normalize();\n for (; ci > 0; ci--) {\n that.halveM();\n if (out.greaterEquals(that)) {\n out.subM(that).normalize();\n }\n }\n return out.trim();\n },\n /** return inverse mod prime p. p must be odd. Binary extended Euclidean algorithm mod p. */\n inverseMod: function (p) {\n var a = new sjcl.bn(1), b = new sjcl.bn(0), x = new sjcl.bn(this), y = new sjcl.bn(p), tmp, i, nz = 1;\n if (!(p.limbs[0] & 1)) {\n throw (new sjcl.exception.invalid(\"inverseMod: p must be odd\"));\n }\n // invariant: y is odd\n do {\n if (x.limbs[0] & 1) {\n if (!x.greaterEquals(y)) {\n // x < y; swap everything\n tmp = x;\n x = y;\n y = tmp;\n tmp = a;\n a = b;\n b = tmp;\n }\n x.subM(y);\n x.normalize();\n if (!a.greaterEquals(b)) {\n a.addM(p);\n }\n a.subM(b);\n }\n // cut everything in half\n x.halveM();\n if (a.limbs[0] & 1) {\n a.addM(p);\n }\n a.normalize();\n a.halveM();\n // check for termination: x ?= 0\n for (i = nz = 0; i < x.limbs.length; i++) {\n nz |= x.limbs[i];\n }\n } while (nz);\n if (!y.equals(1)) {\n throw (new sjcl.exception.invalid(\"inverseMod: p and x must be relatively prime\"));\n }\n return b;\n },\n /** this + that. Does not normalize. */\n add: function (that) {\n return this.copy().addM(that);\n },\n /** this - that. Does not normalize. */\n sub: function (that) {\n return this.copy().subM(that);\n },\n /** this * that. Normalizes and reduces. */\n mul: function (that) {\n if (typeof (that) === \"number\") {\n that = new this._class(that);\n }\n else {\n that.normalize();\n }\n this.normalize();\n var i, j, a = this.limbs, b = that.limbs, al = a.length, bl = b.length, out = new this._class(), c = out.limbs, ai, ii = this.maxMul;\n for (i = 0; i < this.limbs.length + that.limbs.length + 1; i++) {\n c[i] = 0;\n }\n for (i = 0; i < al; i++) {\n ai = a[i];\n for (j = 0; j < bl; j++) {\n c[i + j] += ai * b[j];\n }\n if (!--ii) {\n ii = this.maxMul;\n out.cnormalize();\n }\n }\n return out.cnormalize().reduce();\n },\n /** this ^ 2. Normalizes and reduces. */\n square: function () {\n return this.mul(this);\n },\n /** this ^ n. Uses square-and-multiply. Normalizes and reduces. */\n power: function (l) {\n l = new sjcl.bn(l).normalize().trim().limbs;\n var i, j, out = new this._class(1), pow = this;\n for (i = 0; i < l.length; i++) {\n for (j = 0; j < this.radix; j++) {\n if (l[i] & (1 << j)) {\n out = out.mul(pow);\n }\n if (i == (l.length - 1) && l[i] >> (j + 1) == 0) {\n break;\n }\n pow = pow.square();\n }\n }\n return out;\n },\n /** this * that mod N */\n mulmod: function (that, N) {\n return this.mod(N).mul(that.mod(N)).mod(N);\n },\n /** this ^ x mod N */\n powermod: function (x, N) {\n x = new sjcl.bn(x);\n N = new sjcl.bn(N);\n // Jump to montpowermod if possible.\n if ((N.limbs[0] & 1) == 1) {\n var montOut = this.montpowermod(x, N);\n if (montOut != false) {\n return montOut;\n } // else go to slow powermod\n }\n var i, j, l = x.normalize().trim().limbs, out = new this._class(1), pow = this;\n for (i = 0; i < l.length; i++) {\n for (j = 0; j < this.radix; j++) {\n if (l[i] & (1 << j)) {\n out = out.mulmod(pow, N);\n }\n if (i == (l.length - 1) && l[i] >> (j + 1) == 0) {\n break;\n }\n pow = pow.mulmod(pow, N);\n }\n }\n return out;\n },\n /** this ^ x mod N with Montomery reduction */\n montpowermod: function (x, N) {\n x = new sjcl.bn(x).normalize().trim();\n N = new sjcl.bn(N);\n var i, j, radix = this.radix, out = new this._class(1), pow = this.copy();\n // Generate R as a cap of N.\n var R, s, wind, bitsize = x.bitLength();\n R = new sjcl.bn({\n limbs: N.copy().normalize().trim().limbs.map(function () { return 0; })\n });\n for (s = this.radix; s > 0; s--) {\n if (((N.limbs[N.limbs.length - 1] >> s) & 1) == 1) {\n R.limbs[R.limbs.length - 1] = 1 << s;\n break;\n }\n }\n // Calculate window size as a function of the exponent's size.\n if (bitsize == 0) {\n return this;\n }\n else if (bitsize < 18) {\n wind = 1;\n }\n else if (bitsize < 48) {\n wind = 3;\n }\n else if (bitsize < 144) {\n wind = 4;\n }\n else if (bitsize < 768) {\n wind = 5;\n }\n else {\n wind = 6;\n }\n // Find R' and N' such that R * R' - N * N' = 1.\n var RR = R.copy(), NN = N.copy(), RP = new sjcl.bn(1), NP = new sjcl.bn(0), RT = R.copy();\n while (RT.greaterEquals(1)) {\n RT.halveM();\n if ((RP.limbs[0] & 1) == 0) {\n RP.halveM();\n NP.halveM();\n }\n else {\n RP.addM(NN);\n RP.halveM();\n NP.halveM();\n NP.addM(RR);\n }\n }\n RP = RP.normalize();\n NP = NP.normalize();\n RR.doubleM();\n var R2 = RR.mulmod(RR, N);\n // Check whether the invariant holds.\n // If it doesn't, we can't use Montgomery reduction on this modulus.\n if (!RR.mul(RP).sub(N.mul(NP)).equals(1)) {\n return false;\n }\n var montIn = function (c) { return montMul(c, R2); }, montMul = function (a, b) {\n // Standard Montgomery reduction\n var k, ab, right, abBar, mask = (1 << (s + 1)) - 1;\n ab = a.mul(b);\n right = ab.mul(NP);\n right.limbs = right.limbs.slice(0, R.limbs.length);\n if (right.limbs.length == R.limbs.length) {\n right.limbs[R.limbs.length - 1] &= mask;\n }\n right = right.mul(N);\n abBar = ab.add(right).normalize().trim();\n abBar.limbs = abBar.limbs.slice(R.limbs.length - 1);\n // Division. Equivelent to calling *.halveM() s times.\n for (k = 0; k < abBar.limbs.length; k++) {\n if (k > 0) {\n abBar.limbs[k - 1] |= (abBar.limbs[k] & mask) << (radix - s - 1);\n }\n abBar.limbs[k] = abBar.limbs[k] >> (s + 1);\n }\n if (abBar.greaterEquals(N)) {\n abBar.subM(N);\n }\n return abBar;\n }, montOut = function (c) { return montMul(c, 1); };\n pow = montIn(pow);\n out = montIn(out);\n // Sliding-Window Exponentiation (HAC 14.85)\n var h, precomp = {}, cap = (1 << (wind - 1)) - 1;\n precomp[1] = pow.copy();\n precomp[2] = montMul(pow, pow);\n for (h = 1; h <= cap; h++) {\n precomp[(2 * h) + 1] = montMul(precomp[(2 * h) - 1], precomp[2]);\n }\n var getBit = function (exp, i) {\n var off = i % exp.radix;\n return (exp.limbs[Math.floor(i / exp.radix)] & (1 << off)) >> off;\n };\n for (i = x.bitLength() - 1; i >= 0;) {\n if (getBit(x, i) == 0) {\n // If the next bit is zero:\n // Square, move forward one bit.\n out = montMul(out, out);\n i = i - 1;\n }\n else {\n // If the next bit is one:\n // Find the longest sequence of bits after this one, less than `wind`\n // bits long, that ends with a 1. Convert the sequence into an\n // integer and look up the pre-computed value to add.\n var l = i - wind + 1;\n while (getBit(x, l) == 0) {\n l++;\n }\n var indx = 0;\n for (j = l; j <= i; j++) {\n indx += getBit(x, j) << (j - l);\n out = montMul(out, out);\n }\n out = montMul(out, precomp[indx]);\n i = l - 1;\n }\n }\n return montOut(out);\n },\n trim: function () {\n var l = this.limbs, p;\n do {\n p = l.pop();\n } while (l.length && p === 0);\n l.push(p);\n return this;\n },\n /** Reduce mod a modulus. Stubbed for subclassing. */\n reduce: function () {\n return this;\n },\n /** Reduce and normalize. */\n fullReduce: function () {\n return this.normalize();\n },\n /** Propagate carries. */\n normalize: function () {\n var carry = 0, i, pv = this.placeVal, ipv = this.ipv, l, m, limbs = this.limbs, ll = limbs.length, mask = this.radixMask;\n for (i = 0; i < ll || (carry !== 0 && carry !== -1); i++) {\n l = (limbs[i] || 0) + carry;\n m = limbs[i] = l & mask;\n carry = (l - m) * ipv;\n }\n if (carry === -1) {\n limbs[i - 1] -= pv;\n }\n this.trim();\n return this;\n },\n /** Constant-time normalize. Does not allocate additional space. */\n cnormalize: function () {\n var carry = 0, i, ipv = this.ipv, l, m, limbs = this.limbs, ll = limbs.length, mask = this.radixMask;\n for (i = 0; i < ll - 1; i++) {\n l = limbs[i] + carry;\n m = limbs[i] = l & mask;\n carry = (l - m) * ipv;\n }\n limbs[i] += carry;\n return this;\n },\n /** Serialize to a bit array */\n toBits: function (len) {\n this.fullReduce();\n len = len || this.exponent || this.bitLength();\n var i = Math.floor((len - 1) / 24), w = sjcl.bitArray, e = (len + 7 & -8) % this.radix || this.radix, out = [w.partial(e, this.getLimb(i))];\n for (i--; i >= 0; i--) {\n out = w.concat(out, [w.partial(Math.min(this.radix, len), this.getLimb(i))]);\n len -= this.radix;\n }\n return out;\n },\n /** Return the length in bits, rounded up to the nearest byte. */\n bitLength: function () {\n this.fullReduce();\n var out = this.radix * (this.limbs.length - 1), b = this.limbs[this.limbs.length - 1];\n for (; b; b >>>= 1) {\n out++;\n }\n return out + 7 & -8;\n }\n};\n/** @memberOf sjcl.bn\n* @this { sjcl.bn }\n*/\nsjcl.bn.fromBits = function (bits) {\n var Class = this, out = new Class(), words = [], w = sjcl.bitArray, t = this.prototype, l = Math.min(this.bitLength || 0x100000000, w.bitLength(bits)), e = l % t.radix || t.radix;\n words[0] = w.extract(bits, 0, e);\n for (; e < l; e += t.radix) {\n words.unshift(w.extract(bits, e, t.radix));\n }\n out.limbs = words;\n return out;\n};\nsjcl.bn.prototype.ipv = 1 / (sjcl.bn.prototype.placeVal = Math.pow(2, sjcl.bn.prototype.radix));\nsjcl.bn.prototype.radixMask = (1 << sjcl.bn.prototype.radix) - 1;\n/**\n * Creates a new subclass of bn, based on reduction modulo a pseudo-Mersenne prime,\n * i.e. a prime of the form 2^e + sum(a * 2^b),where the sum is negative and sparse.\n */\nsjcl.bn.pseudoMersennePrime = function (exponent, coeff) {\n /** @constructor\n * @private\n */\n function p(it) {\n this.initWith(it);\n /*if (this.limbs[this.modOffset]) {\n this.reduce();\n }*/\n }\n var ppr = p.prototype = new sjcl.bn(), i, tmp, mo;\n mo = ppr.modOffset = Math.ceil(tmp = exponent / ppr.radix);\n ppr.exponent = exponent;\n ppr.offset = [];\n ppr.factor = [];\n ppr.minOffset = mo;\n ppr.fullMask = 0;\n ppr.fullOffset = [];\n ppr.fullFactor = [];\n ppr.modulus = p.modulus = new sjcl.bn(Math.pow(2, exponent));\n ppr.fullMask = 0 | -Math.pow(2, exponent % ppr.radix);\n for (i = 0; i < coeff.length; i++) {\n ppr.offset[i] = Math.floor(coeff[i][0] / ppr.radix - tmp);\n ppr.fullOffset[i] = Math.floor(coeff[i][0] / ppr.radix) - mo + 1;\n ppr.factor[i] = coeff[i][1] * Math.pow(1 / 2, exponent - coeff[i][0] + ppr.offset[i] * ppr.radix);\n ppr.fullFactor[i] = coeff[i][1] * Math.pow(1 / 2, exponent - coeff[i][0] + ppr.fullOffset[i] * ppr.radix);\n ppr.modulus.addM(new sjcl.bn(Math.pow(2, coeff[i][0]) * coeff[i][1]));\n ppr.minOffset = Math.min(ppr.minOffset, -ppr.offset[i]); // conservative\n }\n ppr._class = p;\n ppr.modulus.cnormalize();\n /** Approximate reduction mod p. May leave a number which is negative or slightly larger than p.\n * @memberof sjcl.bn\n * @this { sjcl.bn }\n */\n ppr.reduce = function () {\n var i, k, l, mo = this.modOffset, limbs = this.limbs, off = this.offset, ol = this.offset.length, fac = this.factor, ll;\n i = this.minOffset;\n while (limbs.length > mo) {\n l = limbs.pop();\n ll = limbs.length;\n for (k = 0; k < ol; k++) {\n limbs[ll + off[k]] -= fac[k] * l;\n }\n i--;\n if (!i) {\n limbs.push(0);\n this.cnormalize();\n i = this.minOffset;\n }\n }\n this.cnormalize();\n return this;\n };\n /** @memberof sjcl.bn\n * @this { sjcl.bn }\n */\n ppr._strongReduce = (ppr.fullMask === -1) ? ppr.reduce : function () {\n var limbs = this.limbs, i = limbs.length - 1, k, l;\n this.reduce();\n if (i === this.modOffset - 1) {\n l = limbs[i] & this.fullMask;\n limbs[i] -= l;\n for (k = 0; k < this.fullOffset.length; k++) {\n limbs[i + this.fullOffset[k]] -= this.fullFactor[k] * l;\n }\n this.normalize();\n }\n };\n /** mostly constant-time, very expensive full reduction.\n * @memberof sjcl.bn\n * @this { sjcl.bn }\n */\n ppr.fullReduce = function () {\n var greater, i;\n // massively above the modulus, may be negative\n this._strongReduce();\n // less than twice the modulus, may be negative\n this.addM(this.modulus);\n this.addM(this.modulus);\n this.normalize();\n // probably 2-3x the modulus\n this._strongReduce();\n // less than the power of 2. still may be more than\n // the modulus\n // HACK: pad out to this length\n for (i = this.limbs.length; i < this.modOffset; i++) {\n this.limbs[i] = 0;\n }\n // constant-time subtract modulus\n greater = this.greaterEquals(this.modulus);\n for (i = 0; i < this.limbs.length; i++) {\n this.limbs[i] -= this.modulus.limbs[i] * greater;\n }\n this.cnormalize();\n return this;\n };\n /** @memberof sjcl.bn\n * @this { sjcl.bn }\n */\n ppr.inverse = function () {\n return (this.power(this.modulus.sub(2)));\n };\n p.fromBits = sjcl.bn.fromBits;\n return p;\n};\n// a small Mersenne prime\nvar sbp = sjcl.bn.pseudoMersennePrime;\nsjcl.bn.prime = {\n p127: sbp(127, [[0, -1]]),\n // Bernstein's prime for Curve25519\n p25519: sbp(255, [[0, -19]]),\n // Koblitz primes\n p192k: sbp(192, [[32, -1], [12, -1], [8, -1], [7, -1], [6, -1], [3, -1], [0, -1]]),\n p224k: sbp(224, [[32, -1], [12, -1], [11, -1], [9, -1], [7, -1], [4, -1], [1, -1], [0, -1]]),\n p256k: sbp(256, [[32, -1], [9, -1], [8, -1], [7, -1], [6, -1], [4, -1], [0, -1]]),\n // NIST primes\n p192: sbp(192, [[0, -1], [64, -1]]),\n p224: sbp(224, [[0, 1], [96, -1]]),\n p256: sbp(256, [[0, -1], [96, 1], [192, 1], [224, -1]]),\n p384: sbp(384, [[0, -1], [32, 1], [96, -1], [128, -1]]),\n p521: sbp(521, [[0, -1]])\n};\nsjcl.bn.random = function (modulus, paranoia) {\n if (typeof modulus !== \"object\") {\n modulus = new sjcl.bn(modulus);\n }\n var words, i, l = modulus.limbs.length, m = modulus.limbs[l - 1] + 1, out = new sjcl.bn();\n while (true) {\n // get a sequence whose first digits make sense\n do {\n words = sjcl.random.randomWords(l, paranoia);\n if (words[l - 1] < 0) {\n words[l - 1] += 0x100000000;\n }\n } while (Math.floor(words[l - 1] / m) === Math.floor(0x100000000 / m));\n words[l - 1] %= m;\n // mask off all the limbs\n for (i = 0; i < l - 1; i++) {\n words[i] &= modulus.radixMask;\n }\n // check the rest of the digitssj\n out.limbs = words;\n if (!out.greaterEquals(modulus)) {\n return out;\n }\n }\n};\n/**\n * base class for all ecc operations.\n * @namespace\n */\nsjcl.ecc = {};\n/**\n * Represents a point on a curve in affine coordinates.\n * @constructor\n * @param {sjcl.ecc.curve} curve The curve that this point lies on.\n * @param {bigInt} x The x coordinate.\n * @param {bigInt} y The y coordinate.\n */\nsjcl.ecc.point = function (curve, x, y) {\n if (x === undefined) {\n this.isIdentity = true;\n }\n else {\n if (x instanceof sjcl.bn) {\n x = new curve.field(x);\n }\n if (y instanceof sjcl.bn) {\n y = new curve.field(y);\n }\n this.x = x;\n this.y = y;\n this.isIdentity = false;\n }\n this.curve = curve;\n};\nsjcl.ecc.point.prototype = {\n toJac: function () {\n return new sjcl.ecc.pointJac(this.curve, this.x, this.y, new this.curve.field(1));\n },\n mult: function (k) {\n return this.toJac().mult(k, this).toAffine();\n },\n /**\n * Multiply this point by k, added to affine2*k2, and return the answer in Jacobian coordinates.\n * @param {bigInt} k The coefficient to multiply this by.\n * @param {bigInt} k2 The coefficient to multiply affine2 this by.\n * @param {sjcl.ecc.point} affine The other point in affine coordinates.\n * @return {sjcl.ecc.pointJac} The result of the multiplication and addition, in Jacobian coordinates.\n */\n mult2: function (k, k2, affine2) {\n return this.toJac().mult2(k, this, k2, affine2).toAffine();\n },\n multiples: function () {\n var m, i, j;\n if (this._multiples === undefined) {\n j = this.toJac().doubl();\n m = this._multiples = [new sjcl.ecc.point(this.curve), this, j.toAffine()];\n for (i = 3; i < 16; i++) {\n j = j.add(this);\n m.push(j.toAffine());\n }\n }\n return this._multiples;\n },\n negate: function () {\n var newY = new this.curve.field(0).sub(this.y).normalize().reduce();\n return new sjcl.ecc.point(this.curve, this.x, newY);\n },\n isValid: function () {\n return this.y.square().equals(this.curve.b.add(this.x.mul(this.curve.a.add(this.x.square()))));\n },\n toBits: function () {\n return sjcl.bitArray.concat(this.x.toBits(), this.y.toBits());\n }\n};\n/**\n * Represents a point on a curve in Jacobian coordinates. Coordinates can be specified as bigInts or strings (which\n * will be converted to bigInts).\n *\n * @constructor\n * @param {bigInt/string} x The x coordinate.\n * @param {bigInt/string} y The y coordinate.\n * @param {bigInt/string} z The z coordinate.\n * @param {sjcl.ecc.curve} curve The curve that this point lies on.\n */\nsjcl.ecc.pointJac = function (curve, x, y, z) {\n if (x === undefined) {\n this.isIdentity = true;\n }\n else {\n this.x = x;\n this.y = y;\n this.z = z;\n this.isIdentity = false;\n }\n this.curve = curve;\n};\nsjcl.ecc.pointJac.prototype = {\n /**\n * Adds S and T and returns the result in Jacobian coordinates. Note that S must be in Jacobian coordinates and T must be in affine coordinates.\n * @param {sjcl.ecc.pointJac} S One of the points to add, in Jacobian coordinates.\n * @param {sjcl.ecc.point} T The other point to add, in affine coordinates.\n * @return {sjcl.ecc.pointJac} The sum of the two points, in Jacobian coordinates.\n */\n add: function (T) {\n var S = this, sz2, c, d, c2, x1, x2, x, y1, y2, y, z;\n if (S.curve !== T.curve) {\n throw new sjcl.exception.invalid(\"sjcl.ecc.add(): Points must be on the same curve to add them!\");\n }\n if (S.isIdentity) {\n return T.toJac();\n }\n else if (T.isIdentity) {\n return S;\n }\n sz2 = S.z.square();\n c = T.x.mul(sz2).subM(S.x);\n if (c.equals(0)) {\n if (S.y.equals(T.y.mul(sz2.mul(S.z)))) {\n // same point\n return S.doubl();\n }\n else {\n // inverses\n return new sjcl.ecc.pointJac(S.curve);\n }\n }\n d = T.y.mul(sz2.mul(S.z)).subM(S.y);\n c2 = c.square();\n x1 = d.square();\n x2 = c.square().mul(c).addM(S.x.add(S.x).mul(c2));\n x = x1.subM(x2);\n y1 = S.x.mul(c2).subM(x).mul(d);\n y2 = S.y.mul(c.square().mul(c));\n y = y1.subM(y2);\n z = S.z.mul(c);\n return new sjcl.ecc.pointJac(this.curve, x, y, z);\n },\n /**\n * doubles this point.\n * @return {sjcl.ecc.pointJac} The doubled point.\n */\n doubl: function () {\n if (this.isIdentity) {\n return this;\n }\n var y2 = this.y.square(), a = y2.mul(this.x.mul(4)), b = y2.square().mul(8), z2 = this.z.square(), c = this.curve.a.toString() == (new sjcl.bn(-3)).toString() ?\n this.x.sub(z2).mul(3).mul(this.x.add(z2)) :\n this.x.square().mul(3).add(z2.square().mul(this.curve.a)), x = c.square().subM(a).subM(a), y = a.sub(x).mul(c).subM(b), z = this.y.add(this.y).mul(this.z);\n return new sjcl.ecc.pointJac(this.curve, x, y, z);\n },\n /**\n * Returns a copy of this point converted to affine coordinates.\n * @return {sjcl.ecc.point} The converted point.\n */\n toAffine: function () {\n if (this.isIdentity || this.z.equals(0)) {\n return new sjcl.ecc.point(this.curve);\n }\n var zi = this.z.inverse(), zi2 = zi.square();\n return new sjcl.ecc.point(this.curve, this.x.mul(zi2).fullReduce(), this.y.mul(zi2.mul(zi)).fullReduce());\n },\n /**\n * Multiply this point by k and return the answer in Jacobian coordinates.\n * @param {bigInt} k The coefficient to multiply by.\n * @param {sjcl.ecc.point} affine This point in affine coordinates.\n * @return {sjcl.ecc.pointJac} The result of the multiplication, in Jacobian coordinates.\n */\n mult: function (k, affine) {\n if (typeof (k) === \"number\") {\n k = [k];\n }\n else if (k.limbs !== undefined) {\n k = k.normalize().limbs;\n }\n var i, j, out = new sjcl.ecc.point(this.curve).toJac(), multiples = affine.multiples();\n for (i = k.length - 1; i >= 0; i--) {\n for (j = sjcl.bn.prototype.radix - 4; j >= 0; j -= 4) {\n out = out.doubl().doubl().doubl().doubl().add(multiples[k[i] >> j & 0xF]);\n }\n }\n return out;\n },\n /**\n * Multiply this point by k, added to affine2*k2, and return the answer in Jacobian coordinates.\n * @param {bigInt} k The coefficient to multiply this by.\n * @param {sjcl.ecc.point} affine This point in affine coordinates.\n * @param {bigInt} k2 The coefficient to multiply affine2 this by.\n * @param {sjcl.ecc.point} affine The other point in affine coordinates.\n * @return {sjcl.ecc.pointJac} The result of the multiplication and addition, in Jacobian coordinates.\n */\n mult2: function (k1, affine, k2, affine2) {\n if (typeof (k1) === \"number\") {\n k1 = [k1];\n }\n else if (k1.limbs !== undefined) {\n k1 = k1.normalize().limbs;\n }\n if (typeof (k2) === \"number\") {\n k2 = [k2];\n }\n else if (k2.limbs !== undefined) {\n k2 = k2.normalize().limbs;\n }\n var i, j, out = new sjcl.ecc.point(this.curve).toJac(), m1 = affine.multiples(), m2 = affine2.multiples(), l1, l2;\n for (i = Math.max(k1.length, k2.length) - 1; i >= 0; i--) {\n l1 = k1[i] | 0;\n l2 = k2[i] | 0;\n for (j = sjcl.bn.prototype.radix - 4; j >= 0; j -= 4) {\n out = out.doubl().doubl().doubl().doubl().add(m1[l1 >> j & 0xF]).add(m2[l2 >> j & 0xF]);\n }\n }\n return out;\n },\n negate: function () {\n return this.toAffine().negate().toJac();\n },\n isValid: function () {\n var z2 = this.z.square(), z4 = z2.square(), z6 = z4.mul(z2);\n return this.y.square().equals(this.curve.b.mul(z6).add(this.x.mul(this.curve.a.mul(z4).add(this.x.square()))));\n }\n};\n/**\n * Construct an elliptic curve. Most users will not use this and instead start with one of the NIST curves defined below.\n *\n * @constructor\n * @param {bigInt} p The prime modulus.\n * @param {bigInt} r The prime order of the curve.\n * @param {bigInt} a The constant a in the equation of the curve y^2 = x^3 + ax + b (for NIST curves, a is always -3).\n * @param {bigInt} x The x coordinate of a base point of the curve.\n * @param {bigInt} y The y coordinate of a base point of the curve.\n */\nsjcl.ecc.curve = function (Field, r, a, b, x, y) {\n this.field = Field;\n this.r = new sjcl.bn(r);\n this.a = new Field(a);\n this.b = new Field(b);\n this.G = new sjcl.ecc.point(this, new Field(x), new Field(y));\n};\nsjcl.ecc.curve.prototype.fromBits = function (bits) {\n var w = sjcl.bitArray, l = this.field.prototype.exponent + 7 & -8, p = new sjcl.ecc.point(this, this.field.fromBits(w.bitSlice(bits, 0, l)), this.field.fromBits(w.bitSlice(bits, l, 2 * l)));\n if (!p.isValid()) {\n throw new sjcl.exception.corrupt(\"not on the curve!\");\n }\n return p;\n};\nsjcl.ecc.curves = {\n c192: new sjcl.ecc.curve(sjcl.bn.prime.p192, \"0xffffffffffffffffffffffff99def836146bc9b1b4d22831\", -3, \"0x64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1\", \"0x188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012\", \"0x07192b95ffc8da78631011ed6b24cdd573f977a11e794811\"),\n c224: new sjcl.ecc.curve(sjcl.bn.prime.p224, \"0xffffffffffffffffffffffffffff16a2e0b8f03e13dd29455c5c2a3d\", -3, \"0xb4050a850c04b3abf54132565044b0b7d7bfd8ba270b39432355ffb4\", \"0xb70e0cbd6bb4bf7f321390b94a03c1d356c21122343280d6115c1d21\", \"0xbd376388b5f723fb4c22dfe6cd4375a05a07476444d5819985007e34\"),\n c256: new sjcl.ecc.curve(sjcl.bn.prime.p256, \"0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551\", -3, \"0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b\", \"0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296\", \"0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5\"),\n c384: new sjcl.ecc.curve(sjcl.bn.prime.p384, \"0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973\", -3, \"0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef\", \"0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7\", \"0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f\"),\n c521: new sjcl.ecc.curve(sjcl.bn.prime.p521, \"0x1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409\", -3, \"0x051953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573DF883D2C34F1EF451FD46B503F00\", \"0xC6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66\", \"0x11839296A789A3BC0045C8A5FB42C7D1BD998F54449579B446817AFBD17273E662C97EE72995EF42640C550B9013FAD0761353C7086A272C24088BE94769FD16650\"),\n k192: new sjcl.ecc.curve(sjcl.bn.prime.p192k, \"0xfffffffffffffffffffffffe26f2fc170f69466a74defd8d\", 0, 3, \"0xdb4ff10ec057e9ae26b07d0280b7f4341da5d1b1eae06c7d\", \"0x9b2f2f6d9c5628a7844163d015be86344082aa88d95e2f9d\"),\n k224: new sjcl.ecc.curve(sjcl.bn.prime.p224k, \"0x010000000000000000000000000001dce8d2ec6184caf0a971769fb1f7\", 0, 5, \"0xa1455b334df099df30fc28a169a467e9e47075a90f7e650eb6b7a45c\", \"0x7e089fed7fba344282cafbd6f7e319f7c0b0bd59e2ca4bdb556d61a5\"),\n k256: new sjcl.ecc.curve(sjcl.bn.prime.p256k, \"0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141\", 0, 7, \"0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798\", \"0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8\")\n};\nsjcl.ecc.curveName = function (curve) {\n var curcurve;\n for (curcurve in sjcl.ecc.curves) {\n if (sjcl.ecc.curves.hasOwnProperty(curcurve)) {\n if (sjcl.ecc.curves[curcurve] === curve) {\n return curcurve;\n }\n }\n }\n throw new sjcl.exception.invalid(\"no such curve\");\n};\nsjcl.ecc.deserialize = function (key) {\n var types = [\"elGamal\", \"ecdsa\"];\n if (!key || !key.curve || !sjcl.ecc.curves[key.curve]) {\n throw new sjcl.exception.invalid(\"invalid serialization\");\n }\n if (types.indexOf(key.type) === -1) {\n throw new sjcl.exception.invalid(\"invalid type\");\n }\n var curve = sjcl.ecc.curves[key.curve];\n if (key.secretKey) {\n if (!key.exponent) {\n throw new sjcl.exception.invalid(\"invalid exponent\");\n }\n var exponent = new sjcl.bn(key.exponent);\n return new sjcl.ecc[key.type].secretKey(curve, exponent);\n }\n else {\n if (!key.point) {\n throw new sjcl.exception.invalid(\"invalid point\");\n }\n var point = curve.fromBits(sjcl.codec.hex.toBits(key.point));\n return new sjcl.ecc[key.type].publicKey(curve, point);\n }\n};\n/** our basicKey classes\n*/\nsjcl.ecc.basicKey = {\n /** ecc publicKey.\n * @constructor\n * @param {curve} curve the elliptic curve\n * @param {point} point the point on the curve\n */\n publicKey: function (curve, point) {\n this._curve = curve;\n this._curveBitLength = curve.r.bitLength();\n if (point instanceof Array) {\n this._point = curve.fromBits(point);\n }\n else {\n this._point = point;\n }\n this.serialize = function () {\n var curveName = sjcl.ecc.curveName(curve);\n return {\n type: this.getType(),\n secretKey: false,\n point: sjcl.codec.hex.fromBits(this._point.toBits()),\n curve: curveName\n };\n };\n /** get this keys point data\n * @return x and y as bitArrays\n */\n this.get = function () {\n var pointbits = this._point.toBits();\n var len = sjcl.bitArray.bitLength(pointbits);\n var x = sjcl.bitArray.bitSlice(pointbits, 0, len / 2);\n var y = sjcl.bitArray.bitSlice(pointbits, len / 2);\n return { x: x, y: y };\n };\n },\n /** ecc secretKey\n * @constructor\n * @param {curve} curve the elliptic curve\n * @param exponent\n */\n secretKey: function (curve, exponent) {\n this._curve = curve;\n this._curveBitLength = curve.r.bitLength();\n this._exponent = exponent;\n this.serialize = function () {\n var exponent = this.get();\n var curveName = sjcl.ecc.curveName(curve);\n return {\n type: this.getType(),\n secretKey: true,\n exponent: sjcl.codec.hex.fromBits(exponent),\n curve: curveName\n };\n };\n /** get this keys exponent data\n * @return {bitArray} exponent\n */\n this.get = function () {\n return this._exponent.toBits();\n };\n }\n};\n/** @private */\nsjcl.ecc.basicKey.generateKeys = function (cn) {\n return function generateKeys(curve, paranoia, sec) {\n curve = curve || 256;\n if (typeof curve === \"number\") {\n curve = sjcl.ecc.curves['c' + curve];\n if (curve === undefined) {\n throw new sjcl.exception.invalid(\"no such curve\");\n }\n }\n sec = sec || sjcl.bn.random(curve.r, paranoia);\n var pub = curve.G.mult(sec);\n return { pub: new sjcl.ecc[cn].publicKey(curve, pub),\n sec: new sjcl.ecc[cn].secretKey(curve, sec) };\n };\n};\n/** elGamal keys */\nsjcl.ecc.elGamal = {\n /** generate keys\n * @function\n * @param curve\n * @param {int} paranoia Paranoia for generation (default 6)\n * @param {secretKey} sec secret Key to use. used to get the publicKey for ones secretKey\n */\n generateKeys: sjcl.ecc.basicKey.generateKeys(\"elGamal\"),\n /** elGamal publicKey.\n * @constructor\n * @augments sjcl.ecc.basicKey.publicKey\n */\n publicKey: function (curve, point) {\n sjcl.ecc.basicKey.publicKey.apply(this, arguments);\n },\n /** elGamal secretKey\n * @constructor\n * @augments sjcl.ecc.basicKey.secretKey\n */\n secretKey: function (curve, exponent) {\n sjcl.ecc.basicKey.secretKey.apply(this, arguments);\n }\n};\nsjcl.ecc.elGamal.publicKey.prototype = {\n /** Kem function of elGamal Public Key\n * @param paranoia paranoia to use for randomization.\n * @return {object} key and tag. unkem(tag) with the corresponding secret key results in the key returned.\n */\n kem: function (paranoia) {\n var sec = sjcl.bn.random(this._curve.r, paranoia), tag = this._curve.G.mult(sec).toBits(), key = sjcl.hash.sha256.hash(this._point.mult(sec).toBits());\n return { key: key, tag: tag };\n },\n getType: function () {\n return \"elGamal\";\n }\n};\nsjcl.ecc.elGamal.secretKey.prototype = {\n /** UnKem function of elGamal Secret Key\n * @param {bitArray} tag The Tag to decrypt.\n * @return {bitArray} decrypted key.\n */\n unkem: function (tag) {\n return sjcl.hash.sha256.hash(this._curve.fromBits(tag).mult(this._exponent).toBits());\n },\n /** Diffie-Hellmann function\n * @param {elGamal.publicKey} pk The Public Key to do Diffie-Hellmann with\n * @return {bitArray} diffie-hellmann result for this key combination.\n */\n dh: function (pk) {\n return sjcl.hash.sha256.hash(pk._point.mult(this._exponent).toBits());\n },\n /** Diffie-Hellmann function, compatible with Java generateSecret\n * @param {elGamal.publicKey} pk The Public Key to do Diffie-Hellmann with\n * @return {bitArray} undigested X value, diffie-hellmann result for this key combination,\n * compatible with Java generateSecret().\n */\n dhJavaEc: function (pk) {\n return pk._point.mult(this._exponent).x.toBits();\n },\n getType: function () {\n return \"elGamal\";\n }\n};\n/** ecdsa keys */\nsjcl.ecc.ecdsa = {\n /** generate keys\n * @function\n * @param curve\n * @param {int} paranoia Paranoia for generation (default 6)\n * @param {secretKey} sec secret Key to use. used to get the publicKey for ones secretKey\n */\n generateKeys: sjcl.ecc.basicKey.generateKeys(\"ecdsa\")\n};\n/** ecdsa publicKey.\n* @constructor\n* @augments sjcl.ecc.basicKey.publicKey\n*/\nsjcl.ecc.ecdsa.publicKey = function (curve, point) {\n sjcl.ecc.basicKey.publicKey.apply(this, arguments);\n};\n/** specific functions for ecdsa publicKey. */\nsjcl.ecc.ecdsa.publicKey.prototype = {\n /** Diffie-Hellmann function\n * @param {bitArray} hash hash to verify.\n * @param {bitArray} rs signature bitArray.\n * @param {boolean} fakeLegacyVersion use old legacy version\n */\n verify: function (hash, rs, fakeLegacyVersion) {\n if (sjcl.bitArray.bitLength(hash) > this._curveBitLength) {\n hash = sjcl.bitArray.clamp(hash, this._curveBitLength);\n }\n var w = sjcl.bitArray, R = this._curve.r, l = this._curveBitLength, r = sjcl.bn.fromBits(w.bitSlice(rs, 0, l)), ss = sjcl.bn.fromBits(w.bitSlice(rs, l, 2 * l)), s = fakeLegacyVersion ? ss : ss.inverseMod(R), hG = sjcl.bn.fromBits(hash).mul(s).mod(R), hA = r.mul(s).mod(R), r2 = this._curve.G.mult2(hG, hA, this._point).x;\n if (r.equals(0) || ss.equals(0) || r.greaterEquals(R) || ss.greaterEquals(R) || !r2.equals(r)) {\n if (fakeLegacyVersion === undefined) {\n return this.verify(hash, rs, true);\n }\n else {\n throw (new sjcl.exception.corrupt(\"signature didn't check out\"));\n }\n }\n return true;\n },\n getType: function () {\n return \"ecdsa\";\n }\n};\n/** ecdsa secretKey\n* @constructor\n* @augments sjcl.ecc.basicKey.publicKey\n*/\nsjcl.ecc.ecdsa.secretKey = function (curve, exponent) {\n sjcl.ecc.basicKey.secretKey.apply(this, arguments);\n};\n/** specific functions for ecdsa secretKey. */\nsjcl.ecc.ecdsa.secretKey.prototype = {\n /** Diffie-Hellmann function\n * @param {bitArray} hash hash to sign.\n * @param {int} paranoia paranoia for random number generation\n * @param {boolean} fakeLegacyVersion use old legacy version\n */\n sign: function (hash, paranoia, fakeLegacyVersion, fixedKForTesting) {\n if (sjcl.bitArray.bitLength(hash) > this._curveBitLength) {\n hash = sjcl.bitArray.clamp(hash, this._curveBitLength);\n }\n var R = this._curve.r, l = R.bitLength(), k = fixedKForTesting || sjcl.bn.random(R.sub(1), paranoia).add(1), r = this._curve.G.mult(k).x.mod(R), ss = sjcl.bn.fromBits(hash).add(r.mul(this._exponent)), s = fakeLegacyVersion ? ss.inverseMod(R).mul(k).mod(R)\n : ss.mul(k.inverseMod(R)).mod(R);\n return sjcl.bitArray.concat(r.toBits(l), s.toBits(l));\n },\n getType: function () {\n return \"ecdsa\";\n }\n};\n/** @fileOverview Bit array codec implementations.\n *\n * @author Marco Munizaga\n */\n//patch arraybuffers if they don't exist\nif (typeof (ArrayBuffer) === 'undefined') {\n (function (globals) {\n \"use strict\";\n globals.ArrayBuffer = function () { };\n globals.DataView = function () { };\n }(this));\n}\n/**\n * ArrayBuffer\n * @namespace\n */\nsjcl.codec.arrayBuffer = {\n /** Convert from a bitArray to an ArrayBuffer.\n * Will default to 8byte padding if padding is undefined*/\n fromBits: function (arr, padding, padding_count) {\n var out, i, ol, tmp, smallest;\n padding = padding == undefined ? true : padding;\n padding_count = padding_count || 8;\n if (arr.length === 0) {\n return new ArrayBuffer(0);\n }\n ol = sjcl.bitArray.bitLength(arr) / 8;\n //check to make sure the bitLength is divisible by 8, if it isn't \n //we can't do anything since arraybuffers work with bytes, not bits\n if (sjcl.bitArray.bitLength(arr) % 8 !== 0) {\n throw new sjcl.exception.invalid(\"Invalid bit size, must be divisble by 8 to fit in an arraybuffer correctly\");\n }\n if (padding && ol % padding_count !== 0) {\n ol += padding_count - (ol % padding_count);\n }\n //padded temp for easy copying\n tmp = new DataView(new ArrayBuffer(arr.length * 4));\n for (i = 0; i < arr.length; i++) {\n tmp.setUint32(i * 4, (arr[i] << 32)); //get rid of the higher bits\n }\n //now copy the final message if we are not going to 0 pad\n out = new DataView(new ArrayBuffer(ol));\n //save a step when the tmp and out bytelength are ===\n if (out.byteLength === tmp.byteLength) {\n return tmp.buffer;\n }\n smallest = tmp.byteLength < out.byteLength ? tmp.byteLength : out.byteLength;\n for (i = 0; i < smallest; i++) {\n out.setUint8(i, tmp.getUint8(i));\n }\n return out.buffer;\n },\n /** Convert from an ArrayBuffer to a bitArray. */\n toBits: function (buffer) {\n var i, out = [], len, inView, tmp;\n if (buffer.byteLength === 0) {\n return [];\n }\n inView = new DataView(buffer);\n len = inView.byteLength - inView.byteLength % 4;\n for (var i = 0; i < len; i += 4) {\n out.push(inView.getUint32(i));\n }\n if (inView.byteLength % 4 != 0) {\n tmp = new DataView(new ArrayBuffer(4));\n for (var i = 0, l = inView.byteLength % 4; i < l; i++) {\n //we want the data to the right, because partial slices off the starting bits\n tmp.setUint8(i + 4 - l, inView.getUint8(len + i)); // big-endian, \n }\n out.push(sjcl.bitArray.partial((inView.byteLength % 4) * 8, tmp.getUint32(0)));\n }\n return out;\n },\n /** Prints a hex output of the buffer contents, akin to hexdump **/\n hexDumpBuffer: function (buffer) {\n var stringBufferView = new DataView(buffer);\n var string = '';\n var pad = function (n, width) {\n n = n + '';\n return n.length >= width ? n : new Array(width - n.length + 1).join('0') + n;\n };\n for (var i = 0; i < stringBufferView.byteLength; i += 2) {\n if (i % 16 == 0)\n string += ('\\n' + (i).toString(16) + '\\t');\n string += (pad(stringBufferView.getUint16(i).toString(16), 4) + ' ');\n }\n if (typeof console === undefined) {\n console = console || { log: function () { } }; //fix for IE\n }\n console.log(string.toUpperCase());\n }\n};\n// if(typeof module !== 'undefined' && module.exports){\n// module.exports = sjcl;\n// }\n// if (typeof define === \"function\") {\n// define([], function () {\n// return sjcl;\n// });\n// }\nexports.default = sjcl;\n", null, null, null, null, null, null, null, null, null, "// Generated by rollup-plugin-mjs-entry\n\nimport cjs from './index.js';\n\nexport const base16 = cjs.base16;\nexport const base32 = cjs.base32;\nexport const base32hex = cjs.base32hex;\nexport const base64 = cjs.base64;\nexport const base64url = cjs.base64url;\nexport const codec = cjs.codec;\nexport default cjs;\n", null, "/*!\n * Copyright (c) 2014, GMO GlobalSign\n * Copyright (c) 2015-2022, Peculiar Ventures\n * All rights reserved.\n * \n * Author 2014-2019, Yury Strozhevsky\n * \n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * \n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * \n * * Redistributions in binary form must reproduce the above copyright notice, this\n * list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * \n * * Neither the name of the copyright holder nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n * \n */\n\nimport * as pvtsutils from 'pvtsutils';\nimport * as pvutils from 'pvutils';\n\nfunction assertBigInt() {\r\n if (typeof BigInt === \"undefined\") {\r\n throw new Error(\"BigInt is not defined. Your environment doesn't implement BigInt.\");\r\n }\r\n}\r\nfunction concat(buffers) {\r\n let outputLength = 0;\r\n let prevLength = 0;\r\n for (let i = 0; i < buffers.length; i++) {\r\n const buffer = buffers[i];\r\n outputLength += buffer.byteLength;\r\n }\r\n const retView = new Uint8Array(outputLength);\r\n for (let i = 0; i < buffers.length; i++) {\r\n const buffer = buffers[i];\r\n retView.set(new Uint8Array(buffer), prevLength);\r\n prevLength += buffer.byteLength;\r\n }\r\n return retView.buffer;\r\n}\r\nfunction checkBufferParams(baseBlock, inputBuffer, inputOffset, inputLength) {\r\n if (!(inputBuffer instanceof Uint8Array)) {\r\n baseBlock.error = \"Wrong parameter: inputBuffer must be 'Uint8Array'\";\r\n return false;\r\n }\r\n if (!inputBuffer.byteLength) {\r\n baseBlock.error = \"Wrong parameter: inputBuffer has zero length\";\r\n return false;\r\n }\r\n if (inputOffset < 0) {\r\n baseBlock.error = \"Wrong parameter: inputOffset less than zero\";\r\n return false;\r\n }\r\n if (inputLength < 0) {\r\n baseBlock.error = \"Wrong parameter: inputLength less than zero\";\r\n return false;\r\n }\r\n if ((inputBuffer.byteLength - inputOffset - inputLength) < 0) {\r\n baseBlock.error = \"End of input reached before message was fully decoded (inconsistent offset and length values)\";\r\n return false;\r\n }\r\n return true;\r\n}\n\nclass ViewWriter {\r\n constructor() {\r\n this.items = [];\r\n }\r\n write(buf) {\r\n this.items.push(buf);\r\n }\r\n final() {\r\n return concat(this.items);\r\n }\r\n}\n\nconst powers2 = [new Uint8Array([1])];\r\nconst digitsString = \"0123456789\";\r\nconst NAME = \"name\";\r\nconst VALUE_HEX_VIEW = \"valueHexView\";\r\nconst IS_HEX_ONLY = \"isHexOnly\";\r\nconst ID_BLOCK = \"idBlock\";\r\nconst TAG_CLASS = \"tagClass\";\r\nconst TAG_NUMBER = \"tagNumber\";\r\nconst IS_CONSTRUCTED = \"isConstructed\";\r\nconst FROM_BER = \"fromBER\";\r\nconst TO_BER = \"toBER\";\r\nconst LOCAL = \"local\";\r\nconst EMPTY_STRING = \"\";\r\nconst EMPTY_BUFFER = new ArrayBuffer(0);\r\nconst EMPTY_VIEW = new Uint8Array(0);\r\nconst END_OF_CONTENT_NAME = \"EndOfContent\";\r\nconst OCTET_STRING_NAME = \"OCTET STRING\";\r\nconst BIT_STRING_NAME = \"BIT STRING\";\n\nfunction HexBlock(BaseClass) {\r\n var _a;\r\n return _a = class Some extends BaseClass {\r\n constructor(...args) {\r\n var _a;\r\n super(...args);\r\n const params = args[0] || {};\r\n this.isHexOnly = (_a = params.isHexOnly) !== null && _a !== void 0 ? _a : false;\r\n this.valueHexView = params.valueHex ? pvtsutils.BufferSourceConverter.toUint8Array(params.valueHex) : EMPTY_VIEW;\r\n }\r\n get valueHex() {\r\n return this.valueHexView.slice().buffer;\r\n }\r\n set valueHex(value) {\r\n this.valueHexView = new Uint8Array(value);\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n const view = inputBuffer instanceof ArrayBuffer ? new Uint8Array(inputBuffer) : inputBuffer;\r\n if (!checkBufferParams(this, view, inputOffset, inputLength)) {\r\n return -1;\r\n }\r\n const endLength = inputOffset + inputLength;\r\n this.valueHexView = view.subarray(inputOffset, endLength);\r\n if (!this.valueHexView.length) {\r\n this.warnings.push(\"Zero buffer length\");\r\n return inputOffset;\r\n }\r\n this.blockLength = inputLength;\r\n return endLength;\r\n }\r\n toBER(sizeOnly = false) {\r\n if (!this.isHexOnly) {\r\n this.error = \"Flag 'isHexOnly' is not set, abort\";\r\n return EMPTY_BUFFER;\r\n }\r\n if (sizeOnly) {\r\n return new ArrayBuffer(this.valueHexView.byteLength);\r\n }\r\n return (this.valueHexView.byteLength === this.valueHexView.buffer.byteLength)\r\n ? this.valueHexView.buffer\r\n : this.valueHexView.slice().buffer;\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n isHexOnly: this.isHexOnly,\r\n valueHex: pvtsutils.Convert.ToHex(this.valueHexView),\r\n };\r\n }\r\n },\r\n _a.NAME = \"hexBlock\",\r\n _a;\r\n}\n\nclass LocalBaseBlock {\r\n constructor({ blockLength = 0, error = EMPTY_STRING, warnings = [], valueBeforeDecode = EMPTY_VIEW, } = {}) {\r\n this.blockLength = blockLength;\r\n this.error = error;\r\n this.warnings = warnings;\r\n this.valueBeforeDecodeView = pvtsutils.BufferSourceConverter.toUint8Array(valueBeforeDecode);\r\n }\r\n static blockName() {\r\n return this.NAME;\r\n }\r\n get valueBeforeDecode() {\r\n return this.valueBeforeDecodeView.slice().buffer;\r\n }\r\n set valueBeforeDecode(value) {\r\n this.valueBeforeDecodeView = new Uint8Array(value);\r\n }\r\n toJSON() {\r\n return {\r\n blockName: this.constructor.NAME,\r\n blockLength: this.blockLength,\r\n error: this.error,\r\n warnings: this.warnings,\r\n valueBeforeDecode: pvtsutils.Convert.ToHex(this.valueBeforeDecodeView),\r\n };\r\n }\r\n}\r\nLocalBaseBlock.NAME = \"baseBlock\";\n\nclass ValueBlock extends LocalBaseBlock {\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n throw TypeError(\"User need to make a specific function in a class which extends 'ValueBlock'\");\r\n }\r\n toBER(sizeOnly, writer) {\r\n throw TypeError(\"User need to make a specific function in a class which extends 'ValueBlock'\");\r\n }\r\n}\r\nValueBlock.NAME = \"valueBlock\";\n\nclass LocalIdentificationBlock extends HexBlock(LocalBaseBlock) {\r\n constructor({ idBlock = {}, } = {}) {\r\n var _a, _b, _c, _d;\r\n super();\r\n if (idBlock) {\r\n this.isHexOnly = (_a = idBlock.isHexOnly) !== null && _a !== void 0 ? _a : false;\r\n this.valueHexView = idBlock.valueHex ? pvtsutils.BufferSourceConverter.toUint8Array(idBlock.valueHex) : EMPTY_VIEW;\r\n this.tagClass = (_b = idBlock.tagClass) !== null && _b !== void 0 ? _b : -1;\r\n this.tagNumber = (_c = idBlock.tagNumber) !== null && _c !== void 0 ? _c : -1;\r\n this.isConstructed = (_d = idBlock.isConstructed) !== null && _d !== void 0 ? _d : false;\r\n }\r\n else {\r\n this.tagClass = -1;\r\n this.tagNumber = -1;\r\n this.isConstructed = false;\r\n }\r\n }\r\n toBER(sizeOnly = false) {\r\n let firstOctet = 0;\r\n switch (this.tagClass) {\r\n case 1:\r\n firstOctet |= 0x00;\r\n break;\r\n case 2:\r\n firstOctet |= 0x40;\r\n break;\r\n case 3:\r\n firstOctet |= 0x80;\r\n break;\r\n case 4:\r\n firstOctet |= 0xC0;\r\n break;\r\n default:\r\n this.error = \"Unknown tag class\";\r\n return EMPTY_BUFFER;\r\n }\r\n if (this.isConstructed)\r\n firstOctet |= 0x20;\r\n if (this.tagNumber < 31 && !this.isHexOnly) {\r\n const retView = new Uint8Array(1);\r\n if (!sizeOnly) {\r\n let number = this.tagNumber;\r\n number &= 0x1F;\r\n firstOctet |= number;\r\n retView[0] = firstOctet;\r\n }\r\n return retView.buffer;\r\n }\r\n if (!this.isHexOnly) {\r\n const encodedBuf = pvutils.utilToBase(this.tagNumber, 7);\r\n const encodedView = new Uint8Array(encodedBuf);\r\n const size = encodedBuf.byteLength;\r\n const retView = new Uint8Array(size + 1);\r\n retView[0] = (firstOctet | 0x1F);\r\n if (!sizeOnly) {\r\n for (let i = 0; i < (size - 1); i++)\r\n retView[i + 1] = encodedView[i] | 0x80;\r\n retView[size] = encodedView[size - 1];\r\n }\r\n return retView.buffer;\r\n }\r\n const retView = new Uint8Array(this.valueHexView.byteLength + 1);\r\n retView[0] = (firstOctet | 0x1F);\r\n if (!sizeOnly) {\r\n const curView = this.valueHexView;\r\n for (let i = 0; i < (curView.length - 1); i++)\r\n retView[i + 1] = curView[i] | 0x80;\r\n retView[this.valueHexView.byteLength] = curView[curView.length - 1];\r\n }\r\n return retView.buffer;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n const inputView = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer);\r\n if (!checkBufferParams(this, inputView, inputOffset, inputLength)) {\r\n return -1;\r\n }\r\n const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength);\r\n if (intBuffer.length === 0) {\r\n this.error = \"Zero buffer length\";\r\n return -1;\r\n }\r\n const tagClassMask = intBuffer[0] & 0xC0;\r\n switch (tagClassMask) {\r\n case 0x00:\r\n this.tagClass = (1);\r\n break;\r\n case 0x40:\r\n this.tagClass = (2);\r\n break;\r\n case 0x80:\r\n this.tagClass = (3);\r\n break;\r\n case 0xC0:\r\n this.tagClass = (4);\r\n break;\r\n default:\r\n this.error = \"Unknown tag class\";\r\n return -1;\r\n }\r\n this.isConstructed = (intBuffer[0] & 0x20) === 0x20;\r\n this.isHexOnly = false;\r\n const tagNumberMask = intBuffer[0] & 0x1F;\r\n if (tagNumberMask !== 0x1F) {\r\n this.tagNumber = (tagNumberMask);\r\n this.blockLength = 1;\r\n }\r\n else {\r\n let count = 1;\r\n let intTagNumberBuffer = this.valueHexView = new Uint8Array(255);\r\n let tagNumberBufferMaxLength = 255;\r\n while (intBuffer[count] & 0x80) {\r\n intTagNumberBuffer[count - 1] = intBuffer[count] & 0x7F;\r\n count++;\r\n if (count >= intBuffer.length) {\r\n this.error = \"End of input reached before message was fully decoded\";\r\n return -1;\r\n }\r\n if (count === tagNumberBufferMaxLength) {\r\n tagNumberBufferMaxLength += 255;\r\n const tempBufferView = new Uint8Array(tagNumberBufferMaxLength);\r\n for (let i = 0; i < intTagNumberBuffer.length; i++)\r\n tempBufferView[i] = intTagNumberBuffer[i];\r\n intTagNumberBuffer = this.valueHexView = new Uint8Array(tagNumberBufferMaxLength);\r\n }\r\n }\r\n this.blockLength = (count + 1);\r\n intTagNumberBuffer[count - 1] = intBuffer[count] & 0x7F;\r\n const tempBufferView = new Uint8Array(count);\r\n for (let i = 0; i < count; i++)\r\n tempBufferView[i] = intTagNumberBuffer[i];\r\n intTagNumberBuffer = this.valueHexView = new Uint8Array(count);\r\n intTagNumberBuffer.set(tempBufferView);\r\n if (this.blockLength <= 9)\r\n this.tagNumber = pvutils.utilFromBase(intTagNumberBuffer, 7);\r\n else {\r\n this.isHexOnly = true;\r\n this.warnings.push(\"Tag too long, represented as hex-coded\");\r\n }\r\n }\r\n if (((this.tagClass === 1)) &&\r\n (this.isConstructed)) {\r\n switch (this.tagNumber) {\r\n case 1:\r\n case 2:\r\n case 5:\r\n case 6:\r\n case 9:\r\n case 13:\r\n case 14:\r\n case 23:\r\n case 24:\r\n case 31:\r\n case 32:\r\n case 33:\r\n case 34:\r\n this.error = \"Constructed encoding used for primitive type\";\r\n return -1;\r\n }\r\n }\r\n return (inputOffset + this.blockLength);\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n tagClass: this.tagClass,\r\n tagNumber: this.tagNumber,\r\n isConstructed: this.isConstructed,\r\n };\r\n }\r\n}\r\nLocalIdentificationBlock.NAME = \"identificationBlock\";\n\nclass LocalLengthBlock extends LocalBaseBlock {\r\n constructor({ lenBlock = {}, } = {}) {\r\n var _a, _b, _c;\r\n super();\r\n this.isIndefiniteForm = (_a = lenBlock.isIndefiniteForm) !== null && _a !== void 0 ? _a : false;\r\n this.longFormUsed = (_b = lenBlock.longFormUsed) !== null && _b !== void 0 ? _b : false;\r\n this.length = (_c = lenBlock.length) !== null && _c !== void 0 ? _c : 0;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n const view = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer);\r\n if (!checkBufferParams(this, view, inputOffset, inputLength)) {\r\n return -1;\r\n }\r\n const intBuffer = view.subarray(inputOffset, inputOffset + inputLength);\r\n if (intBuffer.length === 0) {\r\n this.error = \"Zero buffer length\";\r\n return -1;\r\n }\r\n if (intBuffer[0] === 0xFF) {\r\n this.error = \"Length block 0xFF is reserved by standard\";\r\n return -1;\r\n }\r\n this.isIndefiniteForm = intBuffer[0] === 0x80;\r\n if (this.isIndefiniteForm) {\r\n this.blockLength = 1;\r\n return (inputOffset + this.blockLength);\r\n }\r\n this.longFormUsed = !!(intBuffer[0] & 0x80);\r\n if (this.longFormUsed === false) {\r\n this.length = (intBuffer[0]);\r\n this.blockLength = 1;\r\n return (inputOffset + this.blockLength);\r\n }\r\n const count = intBuffer[0] & 0x7F;\r\n if (count > 8) {\r\n this.error = \"Too big integer\";\r\n return -1;\r\n }\r\n if ((count + 1) > intBuffer.length) {\r\n this.error = \"End of input reached before message was fully decoded\";\r\n return -1;\r\n }\r\n const lenOffset = inputOffset + 1;\r\n const lengthBufferView = view.subarray(lenOffset, lenOffset + count);\r\n if (lengthBufferView[count - 1] === 0x00)\r\n this.warnings.push(\"Needlessly long encoded length\");\r\n this.length = pvutils.utilFromBase(lengthBufferView, 8);\r\n if (this.longFormUsed && (this.length <= 127))\r\n this.warnings.push(\"Unnecessary usage of long length form\");\r\n this.blockLength = count + 1;\r\n return (inputOffset + this.blockLength);\r\n }\r\n toBER(sizeOnly = false) {\r\n let retBuf;\r\n let retView;\r\n if (this.length > 127)\r\n this.longFormUsed = true;\r\n if (this.isIndefiniteForm) {\r\n retBuf = new ArrayBuffer(1);\r\n if (sizeOnly === false) {\r\n retView = new Uint8Array(retBuf);\r\n retView[0] = 0x80;\r\n }\r\n return retBuf;\r\n }\r\n if (this.longFormUsed) {\r\n const encodedBuf = pvutils.utilToBase(this.length, 8);\r\n if (encodedBuf.byteLength > 127) {\r\n this.error = \"Too big length\";\r\n return (EMPTY_BUFFER);\r\n }\r\n retBuf = new ArrayBuffer(encodedBuf.byteLength + 1);\r\n if (sizeOnly)\r\n return retBuf;\r\n const encodedView = new Uint8Array(encodedBuf);\r\n retView = new Uint8Array(retBuf);\r\n retView[0] = encodedBuf.byteLength | 0x80;\r\n for (let i = 0; i < encodedBuf.byteLength; i++)\r\n retView[i + 1] = encodedView[i];\r\n return retBuf;\r\n }\r\n retBuf = new ArrayBuffer(1);\r\n if (sizeOnly === false) {\r\n retView = new Uint8Array(retBuf);\r\n retView[0] = this.length;\r\n }\r\n return retBuf;\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n isIndefiniteForm: this.isIndefiniteForm,\r\n longFormUsed: this.longFormUsed,\r\n length: this.length,\r\n };\r\n }\r\n}\r\nLocalLengthBlock.NAME = \"lengthBlock\";\n\nconst typeStore = {};\n\nclass BaseBlock extends LocalBaseBlock {\r\n constructor({ name = EMPTY_STRING, optional = false, primitiveSchema, ...parameters } = {}, valueBlockType) {\r\n super(parameters);\r\n this.name = name;\r\n this.optional = optional;\r\n if (primitiveSchema) {\r\n this.primitiveSchema = primitiveSchema;\r\n }\r\n this.idBlock = new LocalIdentificationBlock(parameters);\r\n this.lenBlock = new LocalLengthBlock(parameters);\r\n this.valueBlock = valueBlockType ? new valueBlockType(parameters) : new ValueBlock(parameters);\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n const resultOffset = this.valueBlock.fromBER(inputBuffer, inputOffset, (this.lenBlock.isIndefiniteForm) ? inputLength : this.lenBlock.length);\r\n if (resultOffset === -1) {\r\n this.error = this.valueBlock.error;\r\n return resultOffset;\r\n }\r\n if (!this.idBlock.error.length)\r\n this.blockLength += this.idBlock.blockLength;\r\n if (!this.lenBlock.error.length)\r\n this.blockLength += this.lenBlock.blockLength;\r\n if (!this.valueBlock.error.length)\r\n this.blockLength += this.valueBlock.blockLength;\r\n return resultOffset;\r\n }\r\n toBER(sizeOnly, writer) {\r\n const _writer = writer || new ViewWriter();\r\n if (!writer) {\r\n prepareIndefiniteForm(this);\r\n }\r\n const idBlockBuf = this.idBlock.toBER(sizeOnly);\r\n _writer.write(idBlockBuf);\r\n if (this.lenBlock.isIndefiniteForm) {\r\n _writer.write(new Uint8Array([0x80]).buffer);\r\n this.valueBlock.toBER(sizeOnly, _writer);\r\n _writer.write(new ArrayBuffer(2));\r\n }\r\n else {\r\n const valueBlockBuf = this.valueBlock.toBER(sizeOnly);\r\n this.lenBlock.length = valueBlockBuf.byteLength;\r\n const lenBlockBuf = this.lenBlock.toBER(sizeOnly);\r\n _writer.write(lenBlockBuf);\r\n _writer.write(valueBlockBuf);\r\n }\r\n if (!writer) {\r\n return _writer.final();\r\n }\r\n return EMPTY_BUFFER;\r\n }\r\n toJSON() {\r\n const object = {\r\n ...super.toJSON(),\r\n idBlock: this.idBlock.toJSON(),\r\n lenBlock: this.lenBlock.toJSON(),\r\n valueBlock: this.valueBlock.toJSON(),\r\n name: this.name,\r\n optional: this.optional,\r\n };\r\n if (this.primitiveSchema)\r\n object.primitiveSchema = this.primitiveSchema.toJSON();\r\n return object;\r\n }\r\n toString(encoding = \"ascii\") {\r\n if (encoding === \"ascii\") {\r\n return this.onAsciiEncoding();\r\n }\r\n return pvtsutils.Convert.ToHex(this.toBER());\r\n }\r\n onAsciiEncoding() {\r\n return `${this.constructor.NAME} : ${pvtsutils.Convert.ToHex(this.valueBlock.valueBeforeDecodeView)}`;\r\n }\r\n isEqual(other) {\r\n if (this === other) {\r\n return true;\r\n }\r\n if (!(other instanceof this.constructor)) {\r\n return false;\r\n }\r\n const thisRaw = this.toBER();\r\n const otherRaw = other.toBER();\r\n return pvutils.isEqualBuffer(thisRaw, otherRaw);\r\n }\r\n}\r\nBaseBlock.NAME = \"BaseBlock\";\r\nfunction prepareIndefiniteForm(baseBlock) {\r\n if (baseBlock instanceof typeStore.Constructed) {\r\n for (const value of baseBlock.valueBlock.value) {\r\n if (prepareIndefiniteForm(value)) {\r\n baseBlock.lenBlock.isIndefiniteForm = true;\r\n }\r\n }\r\n }\r\n return !!baseBlock.lenBlock.isIndefiniteForm;\r\n}\n\nclass BaseStringBlock extends BaseBlock {\r\n constructor({ value = EMPTY_STRING, ...parameters } = {}, stringValueBlockType) {\r\n super(parameters, stringValueBlockType);\r\n if (value) {\r\n this.fromString(value);\r\n }\r\n }\r\n getValue() {\r\n return this.valueBlock.value;\r\n }\r\n setValue(value) {\r\n this.valueBlock.value = value;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n const resultOffset = this.valueBlock.fromBER(inputBuffer, inputOffset, (this.lenBlock.isIndefiniteForm) ? inputLength : this.lenBlock.length);\r\n if (resultOffset === -1) {\r\n this.error = this.valueBlock.error;\r\n return resultOffset;\r\n }\r\n this.fromBuffer(this.valueBlock.valueHexView);\r\n if (!this.idBlock.error.length)\r\n this.blockLength += this.idBlock.blockLength;\r\n if (!this.lenBlock.error.length)\r\n this.blockLength += this.lenBlock.blockLength;\r\n if (!this.valueBlock.error.length)\r\n this.blockLength += this.valueBlock.blockLength;\r\n return resultOffset;\r\n }\r\n onAsciiEncoding() {\r\n return `${this.constructor.NAME} : '${this.valueBlock.value}'`;\r\n }\r\n}\r\nBaseStringBlock.NAME = \"BaseStringBlock\";\n\nclass LocalPrimitiveValueBlock extends HexBlock(ValueBlock) {\r\n constructor({ isHexOnly = true, ...parameters } = {}) {\r\n super(parameters);\r\n this.isHexOnly = isHexOnly;\r\n }\r\n}\r\nLocalPrimitiveValueBlock.NAME = \"PrimitiveValueBlock\";\n\nvar _a$w;\r\nclass Primitive extends BaseBlock {\r\n constructor(parameters = {}) {\r\n super(parameters, LocalPrimitiveValueBlock);\r\n this.idBlock.isConstructed = false;\r\n }\r\n}\r\n_a$w = Primitive;\r\n(() => {\r\n typeStore.Primitive = _a$w;\r\n})();\r\nPrimitive.NAME = \"PRIMITIVE\";\n\nfunction localChangeType(inputObject, newType) {\r\n if (inputObject instanceof newType) {\r\n return inputObject;\r\n }\r\n const newObject = new newType();\r\n newObject.idBlock = inputObject.idBlock;\r\n newObject.lenBlock = inputObject.lenBlock;\r\n newObject.warnings = inputObject.warnings;\r\n newObject.valueBeforeDecodeView = inputObject.valueBeforeDecodeView;\r\n return newObject;\r\n}\r\nfunction localFromBER(inputBuffer, inputOffset = 0, inputLength = inputBuffer.length) {\r\n const incomingOffset = inputOffset;\r\n let returnObject = new BaseBlock({}, ValueBlock);\r\n const baseBlock = new LocalBaseBlock();\r\n if (!checkBufferParams(baseBlock, inputBuffer, inputOffset, inputLength)) {\r\n returnObject.error = baseBlock.error;\r\n return {\r\n offset: -1,\r\n result: returnObject\r\n };\r\n }\r\n const intBuffer = inputBuffer.subarray(inputOffset, inputOffset + inputLength);\r\n if (!intBuffer.length) {\r\n returnObject.error = \"Zero buffer length\";\r\n return {\r\n offset: -1,\r\n result: returnObject\r\n };\r\n }\r\n let resultOffset = returnObject.idBlock.fromBER(inputBuffer, inputOffset, inputLength);\r\n if (returnObject.idBlock.warnings.length) {\r\n returnObject.warnings.concat(returnObject.idBlock.warnings);\r\n }\r\n if (resultOffset === -1) {\r\n returnObject.error = returnObject.idBlock.error;\r\n return {\r\n offset: -1,\r\n result: returnObject\r\n };\r\n }\r\n inputOffset = resultOffset;\r\n inputLength -= returnObject.idBlock.blockLength;\r\n resultOffset = returnObject.lenBlock.fromBER(inputBuffer, inputOffset, inputLength);\r\n if (returnObject.lenBlock.warnings.length) {\r\n returnObject.warnings.concat(returnObject.lenBlock.warnings);\r\n }\r\n if (resultOffset === -1) {\r\n returnObject.error = returnObject.lenBlock.error;\r\n return {\r\n offset: -1,\r\n result: returnObject\r\n };\r\n }\r\n inputOffset = resultOffset;\r\n inputLength -= returnObject.lenBlock.blockLength;\r\n if (!returnObject.idBlock.isConstructed &&\r\n returnObject.lenBlock.isIndefiniteForm) {\r\n returnObject.error = \"Indefinite length form used for primitive encoding form\";\r\n return {\r\n offset: -1,\r\n result: returnObject\r\n };\r\n }\r\n let newASN1Type = BaseBlock;\r\n switch (returnObject.idBlock.tagClass) {\r\n case 1:\r\n if ((returnObject.idBlock.tagNumber >= 37) &&\r\n (returnObject.idBlock.isHexOnly === false)) {\r\n returnObject.error = \"UNIVERSAL 37 and upper tags are reserved by ASN.1 standard\";\r\n return {\r\n offset: -1,\r\n result: returnObject\r\n };\r\n }\r\n switch (returnObject.idBlock.tagNumber) {\r\n case 0:\r\n if ((returnObject.idBlock.isConstructed) &&\r\n (returnObject.lenBlock.length > 0)) {\r\n returnObject.error = \"Type [UNIVERSAL 0] is reserved\";\r\n return {\r\n offset: -1,\r\n result: returnObject\r\n };\r\n }\r\n newASN1Type = typeStore.EndOfContent;\r\n break;\r\n case 1:\r\n newASN1Type = typeStore.Boolean;\r\n break;\r\n case 2:\r\n newASN1Type = typeStore.Integer;\r\n break;\r\n case 3:\r\n newASN1Type = typeStore.BitString;\r\n break;\r\n case 4:\r\n newASN1Type = typeStore.OctetString;\r\n break;\r\n case 5:\r\n newASN1Type = typeStore.Null;\r\n break;\r\n case 6:\r\n newASN1Type = typeStore.ObjectIdentifier;\r\n break;\r\n case 10:\r\n newASN1Type = typeStore.Enumerated;\r\n break;\r\n case 12:\r\n newASN1Type = typeStore.Utf8String;\r\n break;\r\n case 13:\r\n newASN1Type = typeStore.RelativeObjectIdentifier;\r\n break;\r\n case 14:\r\n newASN1Type = typeStore.TIME;\r\n break;\r\n case 15:\r\n returnObject.error = \"[UNIVERSAL 15] is reserved by ASN.1 standard\";\r\n return {\r\n offset: -1,\r\n result: returnObject\r\n };\r\n case 16:\r\n newASN1Type = typeStore.Sequence;\r\n break;\r\n case 17:\r\n newASN1Type = typeStore.Set;\r\n break;\r\n case 18:\r\n newASN1Type = typeStore.NumericString;\r\n break;\r\n case 19:\r\n newASN1Type = typeStore.PrintableString;\r\n break;\r\n case 20:\r\n newASN1Type = typeStore.TeletexString;\r\n break;\r\n case 21:\r\n newASN1Type = typeStore.VideotexString;\r\n break;\r\n case 22:\r\n newASN1Type = typeStore.IA5String;\r\n break;\r\n case 23:\r\n newASN1Type = typeStore.UTCTime;\r\n break;\r\n case 24:\r\n newASN1Type = typeStore.GeneralizedTime;\r\n break;\r\n case 25:\r\n newASN1Type = typeStore.GraphicString;\r\n break;\r\n case 26:\r\n newASN1Type = typeStore.VisibleString;\r\n break;\r\n case 27:\r\n newASN1Type = typeStore.GeneralString;\r\n break;\r\n case 28:\r\n newASN1Type = typeStore.UniversalString;\r\n break;\r\n case 29:\r\n newASN1Type = typeStore.CharacterString;\r\n break;\r\n case 30:\r\n newASN1Type = typeStore.BmpString;\r\n break;\r\n case 31:\r\n newASN1Type = typeStore.DATE;\r\n break;\r\n case 32:\r\n newASN1Type = typeStore.TimeOfDay;\r\n break;\r\n case 33:\r\n newASN1Type = typeStore.DateTime;\r\n break;\r\n case 34:\r\n newASN1Type = typeStore.Duration;\r\n break;\r\n default: {\r\n const newObject = returnObject.idBlock.isConstructed\r\n ? new typeStore.Constructed()\r\n : new typeStore.Primitive();\r\n newObject.idBlock = returnObject.idBlock;\r\n newObject.lenBlock = returnObject.lenBlock;\r\n newObject.warnings = returnObject.warnings;\r\n returnObject = newObject;\r\n }\r\n }\r\n break;\r\n case 2:\r\n case 3:\r\n case 4:\r\n default: {\r\n newASN1Type = returnObject.idBlock.isConstructed\r\n ? typeStore.Constructed\r\n : typeStore.Primitive;\r\n }\r\n }\r\n returnObject = localChangeType(returnObject, newASN1Type);\r\n resultOffset = returnObject.fromBER(inputBuffer, inputOffset, returnObject.lenBlock.isIndefiniteForm ? inputLength : returnObject.lenBlock.length);\r\n returnObject.valueBeforeDecodeView = inputBuffer.subarray(incomingOffset, incomingOffset + returnObject.blockLength);\r\n return {\r\n offset: resultOffset,\r\n result: returnObject\r\n };\r\n}\r\nfunction fromBER(inputBuffer) {\r\n if (!inputBuffer.byteLength) {\r\n const result = new BaseBlock({}, ValueBlock);\r\n result.error = \"Input buffer has zero length\";\r\n return {\r\n offset: -1,\r\n result\r\n };\r\n }\r\n return localFromBER(pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer).slice(), 0, inputBuffer.byteLength);\r\n}\n\nfunction checkLen(indefiniteLength, length) {\r\n if (indefiniteLength) {\r\n return 1;\r\n }\r\n return length;\r\n}\r\nclass LocalConstructedValueBlock extends ValueBlock {\r\n constructor({ value = [], isIndefiniteForm = false, ...parameters } = {}) {\r\n super(parameters);\r\n this.value = value;\r\n this.isIndefiniteForm = isIndefiniteForm;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n const view = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer);\r\n if (!checkBufferParams(this, view, inputOffset, inputLength)) {\r\n return -1;\r\n }\r\n this.valueBeforeDecodeView = view.subarray(inputOffset, inputOffset + inputLength);\r\n if (this.valueBeforeDecodeView.length === 0) {\r\n this.warnings.push(\"Zero buffer length\");\r\n return inputOffset;\r\n }\r\n let currentOffset = inputOffset;\r\n while (checkLen(this.isIndefiniteForm, inputLength) > 0) {\r\n const returnObject = localFromBER(view, currentOffset, inputLength);\r\n if (returnObject.offset === -1) {\r\n this.error = returnObject.result.error;\r\n this.warnings.concat(returnObject.result.warnings);\r\n return -1;\r\n }\r\n currentOffset = returnObject.offset;\r\n this.blockLength += returnObject.result.blockLength;\r\n inputLength -= returnObject.result.blockLength;\r\n this.value.push(returnObject.result);\r\n if (this.isIndefiniteForm && returnObject.result.constructor.NAME === END_OF_CONTENT_NAME) {\r\n break;\r\n }\r\n }\r\n if (this.isIndefiniteForm) {\r\n if (this.value[this.value.length - 1].constructor.NAME === END_OF_CONTENT_NAME) {\r\n this.value.pop();\r\n }\r\n else {\r\n this.warnings.push(\"No EndOfContent block encoded\");\r\n }\r\n }\r\n return currentOffset;\r\n }\r\n toBER(sizeOnly, writer) {\r\n const _writer = writer || new ViewWriter();\r\n for (let i = 0; i < this.value.length; i++) {\r\n this.value[i].toBER(sizeOnly, _writer);\r\n }\r\n if (!writer) {\r\n return _writer.final();\r\n }\r\n return EMPTY_BUFFER;\r\n }\r\n toJSON() {\r\n const object = {\r\n ...super.toJSON(),\r\n isIndefiniteForm: this.isIndefiniteForm,\r\n value: [],\r\n };\r\n for (const value of this.value) {\r\n object.value.push(value.toJSON());\r\n }\r\n return object;\r\n }\r\n}\r\nLocalConstructedValueBlock.NAME = \"ConstructedValueBlock\";\n\nvar _a$v;\r\nclass Constructed extends BaseBlock {\r\n constructor(parameters = {}) {\r\n super(parameters, LocalConstructedValueBlock);\r\n this.idBlock.isConstructed = true;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n this.valueBlock.isIndefiniteForm = this.lenBlock.isIndefiniteForm;\r\n const resultOffset = this.valueBlock.fromBER(inputBuffer, inputOffset, (this.lenBlock.isIndefiniteForm) ? inputLength : this.lenBlock.length);\r\n if (resultOffset === -1) {\r\n this.error = this.valueBlock.error;\r\n return resultOffset;\r\n }\r\n if (!this.idBlock.error.length)\r\n this.blockLength += this.idBlock.blockLength;\r\n if (!this.lenBlock.error.length)\r\n this.blockLength += this.lenBlock.blockLength;\r\n if (!this.valueBlock.error.length)\r\n this.blockLength += this.valueBlock.blockLength;\r\n return resultOffset;\r\n }\r\n onAsciiEncoding() {\r\n const values = [];\r\n for (const value of this.valueBlock.value) {\r\n values.push(value.toString(\"ascii\").split(\"\\n\").map(o => ` ${o}`).join(\"\\n\"));\r\n }\r\n const blockName = this.idBlock.tagClass === 3\r\n ? `[${this.idBlock.tagNumber}]`\r\n : this.constructor.NAME;\r\n return values.length\r\n ? `${blockName} :\\n${values.join(\"\\n\")}`\r\n : `${blockName} :`;\r\n }\r\n}\r\n_a$v = Constructed;\r\n(() => {\r\n typeStore.Constructed = _a$v;\r\n})();\r\nConstructed.NAME = \"CONSTRUCTED\";\n\nclass LocalEndOfContentValueBlock extends ValueBlock {\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n return inputOffset;\r\n }\r\n toBER(sizeOnly) {\r\n return EMPTY_BUFFER;\r\n }\r\n}\r\nLocalEndOfContentValueBlock.override = \"EndOfContentValueBlock\";\n\nvar _a$u;\r\nclass EndOfContent extends BaseBlock {\r\n constructor(parameters = {}) {\r\n super(parameters, LocalEndOfContentValueBlock);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 0;\r\n }\r\n}\r\n_a$u = EndOfContent;\r\n(() => {\r\n typeStore.EndOfContent = _a$u;\r\n})();\r\nEndOfContent.NAME = END_OF_CONTENT_NAME;\n\nvar _a$t;\r\nclass Null extends BaseBlock {\r\n constructor(parameters = {}) {\r\n super(parameters, ValueBlock);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 5;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n if (this.lenBlock.length > 0)\r\n this.warnings.push(\"Non-zero length of value block for Null type\");\r\n if (!this.idBlock.error.length)\r\n this.blockLength += this.idBlock.blockLength;\r\n if (!this.lenBlock.error.length)\r\n this.blockLength += this.lenBlock.blockLength;\r\n this.blockLength += inputLength;\r\n if ((inputOffset + inputLength) > inputBuffer.byteLength) {\r\n this.error = \"End of input reached before message was fully decoded (inconsistent offset and length values)\";\r\n return -1;\r\n }\r\n return (inputOffset + inputLength);\r\n }\r\n toBER(sizeOnly, writer) {\r\n const retBuf = new ArrayBuffer(2);\r\n if (!sizeOnly) {\r\n const retView = new Uint8Array(retBuf);\r\n retView[0] = 0x05;\r\n retView[1] = 0x00;\r\n }\r\n if (writer) {\r\n writer.write(retBuf);\r\n }\r\n return retBuf;\r\n }\r\n onAsciiEncoding() {\r\n return `${this.constructor.NAME}`;\r\n }\r\n}\r\n_a$t = Null;\r\n(() => {\r\n typeStore.Null = _a$t;\r\n})();\r\nNull.NAME = \"NULL\";\n\nclass LocalBooleanValueBlock extends HexBlock(ValueBlock) {\r\n constructor({ value, ...parameters } = {}) {\r\n super(parameters);\r\n if (parameters.valueHex) {\r\n this.valueHexView = pvtsutils.BufferSourceConverter.toUint8Array(parameters.valueHex);\r\n }\r\n else {\r\n this.valueHexView = new Uint8Array(1);\r\n }\r\n if (value) {\r\n this.value = value;\r\n }\r\n }\r\n get value() {\r\n for (const octet of this.valueHexView) {\r\n if (octet > 0) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }\r\n set value(value) {\r\n this.valueHexView[0] = value ? 0xFF : 0x00;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n const inputView = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer);\r\n if (!checkBufferParams(this, inputView, inputOffset, inputLength)) {\r\n return -1;\r\n }\r\n this.valueHexView = inputView.subarray(inputOffset, inputOffset + inputLength);\r\n if (inputLength > 1)\r\n this.warnings.push(\"Boolean value encoded in more then 1 octet\");\r\n this.isHexOnly = true;\r\n pvutils.utilDecodeTC.call(this);\r\n this.blockLength = inputLength;\r\n return (inputOffset + inputLength);\r\n }\r\n toBER() {\r\n return this.valueHexView.slice();\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n value: this.value,\r\n };\r\n }\r\n}\r\nLocalBooleanValueBlock.NAME = \"BooleanValueBlock\";\n\nvar _a$s;\r\nclass Boolean extends BaseBlock {\r\n constructor(parameters = {}) {\r\n super(parameters, LocalBooleanValueBlock);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 1;\r\n }\r\n getValue() {\r\n return this.valueBlock.value;\r\n }\r\n setValue(value) {\r\n this.valueBlock.value = value;\r\n }\r\n onAsciiEncoding() {\r\n return `${this.constructor.NAME} : ${this.getValue}`;\r\n }\r\n}\r\n_a$s = Boolean;\r\n(() => {\r\n typeStore.Boolean = _a$s;\r\n})();\r\nBoolean.NAME = \"BOOLEAN\";\n\nclass LocalOctetStringValueBlock extends HexBlock(LocalConstructedValueBlock) {\r\n constructor({ isConstructed = false, ...parameters } = {}) {\r\n super(parameters);\r\n this.isConstructed = isConstructed;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n let resultOffset = 0;\r\n if (this.isConstructed) {\r\n this.isHexOnly = false;\r\n resultOffset = LocalConstructedValueBlock.prototype.fromBER.call(this, inputBuffer, inputOffset, inputLength);\r\n if (resultOffset === -1)\r\n return resultOffset;\r\n for (let i = 0; i < this.value.length; i++) {\r\n const currentBlockName = this.value[i].constructor.NAME;\r\n if (currentBlockName === END_OF_CONTENT_NAME) {\r\n if (this.isIndefiniteForm)\r\n break;\r\n else {\r\n this.error = \"EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only\";\r\n return -1;\r\n }\r\n }\r\n if (currentBlockName !== OCTET_STRING_NAME) {\r\n this.error = \"OCTET STRING may consists of OCTET STRINGs only\";\r\n return -1;\r\n }\r\n }\r\n }\r\n else {\r\n this.isHexOnly = true;\r\n resultOffset = super.fromBER(inputBuffer, inputOffset, inputLength);\r\n this.blockLength = inputLength;\r\n }\r\n return resultOffset;\r\n }\r\n toBER(sizeOnly, writer) {\r\n if (this.isConstructed)\r\n return LocalConstructedValueBlock.prototype.toBER.call(this, sizeOnly, writer);\r\n return sizeOnly\r\n ? new ArrayBuffer(this.valueHexView.byteLength)\r\n : this.valueHexView.slice().buffer;\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n isConstructed: this.isConstructed,\r\n };\r\n }\r\n}\r\nLocalOctetStringValueBlock.NAME = \"OctetStringValueBlock\";\n\nvar _a$r;\r\nclass OctetString extends BaseBlock {\r\n constructor({ idBlock = {}, lenBlock = {}, ...parameters } = {}) {\r\n var _b, _c;\r\n (_b = parameters.isConstructed) !== null && _b !== void 0 ? _b : (parameters.isConstructed = !!((_c = parameters.value) === null || _c === void 0 ? void 0 : _c.length));\r\n super({\r\n idBlock: {\r\n isConstructed: parameters.isConstructed,\r\n ...idBlock,\r\n },\r\n lenBlock: {\r\n ...lenBlock,\r\n isIndefiniteForm: !!parameters.isIndefiniteForm,\r\n },\r\n ...parameters,\r\n }, LocalOctetStringValueBlock);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 4;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n this.valueBlock.isConstructed = this.idBlock.isConstructed;\r\n this.valueBlock.isIndefiniteForm = this.lenBlock.isIndefiniteForm;\r\n if (inputLength === 0) {\r\n if (this.idBlock.error.length === 0)\r\n this.blockLength += this.idBlock.blockLength;\r\n if (this.lenBlock.error.length === 0)\r\n this.blockLength += this.lenBlock.blockLength;\r\n return inputOffset;\r\n }\r\n if (!this.valueBlock.isConstructed) {\r\n const view = inputBuffer instanceof ArrayBuffer ? new Uint8Array(inputBuffer) : inputBuffer;\r\n const buf = view.subarray(inputOffset, inputOffset + inputLength);\r\n try {\r\n if (buf.byteLength) {\r\n const asn = localFromBER(buf, 0, buf.byteLength);\r\n if (asn.offset !== -1 && asn.offset === inputLength) {\r\n this.valueBlock.value = [asn.result];\r\n }\r\n }\r\n }\r\n catch (e) {\r\n }\r\n }\r\n return super.fromBER(inputBuffer, inputOffset, inputLength);\r\n }\r\n onAsciiEncoding() {\r\n if (this.valueBlock.isConstructed || (this.valueBlock.value && this.valueBlock.value.length)) {\r\n return Constructed.prototype.onAsciiEncoding.call(this);\r\n }\r\n return `${this.constructor.NAME} : ${pvtsutils.Convert.ToHex(this.valueBlock.valueHexView)}`;\r\n }\r\n getValue() {\r\n if (!this.idBlock.isConstructed) {\r\n return this.valueBlock.valueHexView.slice().buffer;\r\n }\r\n const array = [];\r\n for (const content of this.valueBlock.value) {\r\n if (content instanceof OctetString) {\r\n array.push(content.valueBlock.valueHexView);\r\n }\r\n }\r\n return pvtsutils.BufferSourceConverter.concat(array);\r\n }\r\n}\r\n_a$r = OctetString;\r\n(() => {\r\n typeStore.OctetString = _a$r;\r\n})();\r\nOctetString.NAME = OCTET_STRING_NAME;\n\nclass LocalBitStringValueBlock extends HexBlock(LocalConstructedValueBlock) {\r\n constructor({ unusedBits = 0, isConstructed = false, ...parameters } = {}) {\r\n super(parameters);\r\n this.unusedBits = unusedBits;\r\n this.isConstructed = isConstructed;\r\n this.blockLength = this.valueHexView.byteLength;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n if (!inputLength) {\r\n return inputOffset;\r\n }\r\n let resultOffset = -1;\r\n if (this.isConstructed) {\r\n resultOffset = LocalConstructedValueBlock.prototype.fromBER.call(this, inputBuffer, inputOffset, inputLength);\r\n if (resultOffset === -1)\r\n return resultOffset;\r\n for (const value of this.value) {\r\n const currentBlockName = value.constructor.NAME;\r\n if (currentBlockName === END_OF_CONTENT_NAME) {\r\n if (this.isIndefiniteForm)\r\n break;\r\n else {\r\n this.error = \"EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only\";\r\n return -1;\r\n }\r\n }\r\n if (currentBlockName !== BIT_STRING_NAME) {\r\n this.error = \"BIT STRING may consists of BIT STRINGs only\";\r\n return -1;\r\n }\r\n const valueBlock = value.valueBlock;\r\n if ((this.unusedBits > 0) && (valueBlock.unusedBits > 0)) {\r\n this.error = \"Using of \\\"unused bits\\\" inside constructive BIT STRING allowed for least one only\";\r\n return -1;\r\n }\r\n this.unusedBits = valueBlock.unusedBits;\r\n }\r\n return resultOffset;\r\n }\r\n const inputView = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer);\r\n if (!checkBufferParams(this, inputView, inputOffset, inputLength)) {\r\n return -1;\r\n }\r\n const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength);\r\n this.unusedBits = intBuffer[0];\r\n if (this.unusedBits > 7) {\r\n this.error = \"Unused bits for BitString must be in range 0-7\";\r\n return -1;\r\n }\r\n if (!this.unusedBits) {\r\n const buf = intBuffer.subarray(1);\r\n try {\r\n if (buf.byteLength) {\r\n const asn = localFromBER(buf, 0, buf.byteLength);\r\n if (asn.offset !== -1 && asn.offset === (inputLength - 1)) {\r\n this.value = [asn.result];\r\n }\r\n }\r\n }\r\n catch (e) {\r\n }\r\n }\r\n this.valueHexView = intBuffer.subarray(1);\r\n this.blockLength = intBuffer.length;\r\n return (inputOffset + inputLength);\r\n }\r\n toBER(sizeOnly, writer) {\r\n if (this.isConstructed) {\r\n return LocalConstructedValueBlock.prototype.toBER.call(this, sizeOnly, writer);\r\n }\r\n if (sizeOnly) {\r\n return new ArrayBuffer(this.valueHexView.byteLength + 1);\r\n }\r\n if (!this.valueHexView.byteLength) {\r\n return EMPTY_BUFFER;\r\n }\r\n const retView = new Uint8Array(this.valueHexView.length + 1);\r\n retView[0] = this.unusedBits;\r\n retView.set(this.valueHexView, 1);\r\n return retView.buffer;\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n unusedBits: this.unusedBits,\r\n isConstructed: this.isConstructed,\r\n };\r\n }\r\n}\r\nLocalBitStringValueBlock.NAME = \"BitStringValueBlock\";\n\nvar _a$q;\r\nclass BitString extends BaseBlock {\r\n constructor({ idBlock = {}, lenBlock = {}, ...parameters } = {}) {\r\n var _b, _c;\r\n (_b = parameters.isConstructed) !== null && _b !== void 0 ? _b : (parameters.isConstructed = !!((_c = parameters.value) === null || _c === void 0 ? void 0 : _c.length));\r\n super({\r\n idBlock: {\r\n isConstructed: parameters.isConstructed,\r\n ...idBlock,\r\n },\r\n lenBlock: {\r\n ...lenBlock,\r\n isIndefiniteForm: !!parameters.isIndefiniteForm,\r\n },\r\n ...parameters,\r\n }, LocalBitStringValueBlock);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 3;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n this.valueBlock.isConstructed = this.idBlock.isConstructed;\r\n this.valueBlock.isIndefiniteForm = this.lenBlock.isIndefiniteForm;\r\n return super.fromBER(inputBuffer, inputOffset, inputLength);\r\n }\r\n onAsciiEncoding() {\r\n if (this.valueBlock.isConstructed || (this.valueBlock.value && this.valueBlock.value.length)) {\r\n return Constructed.prototype.onAsciiEncoding.call(this);\r\n }\r\n else {\r\n const bits = [];\r\n const valueHex = this.valueBlock.valueHexView;\r\n for (const byte of valueHex) {\r\n bits.push(byte.toString(2).padStart(8, \"0\"));\r\n }\r\n const bitsStr = bits.join(\"\");\r\n return `${this.constructor.NAME} : ${bitsStr.substring(0, bitsStr.length - this.valueBlock.unusedBits)}`;\r\n }\r\n }\r\n}\r\n_a$q = BitString;\r\n(() => {\r\n typeStore.BitString = _a$q;\r\n})();\r\nBitString.NAME = BIT_STRING_NAME;\n\nvar _a$p;\r\nfunction viewAdd(first, second) {\r\n const c = new Uint8Array([0]);\r\n const firstView = new Uint8Array(first);\r\n const secondView = new Uint8Array(second);\r\n let firstViewCopy = firstView.slice(0);\r\n const firstViewCopyLength = firstViewCopy.length - 1;\r\n const secondViewCopy = secondView.slice(0);\r\n const secondViewCopyLength = secondViewCopy.length - 1;\r\n let value = 0;\r\n const max = (secondViewCopyLength < firstViewCopyLength) ? firstViewCopyLength : secondViewCopyLength;\r\n let counter = 0;\r\n for (let i = max; i >= 0; i--, counter++) {\r\n switch (true) {\r\n case (counter < secondViewCopy.length):\r\n value = firstViewCopy[firstViewCopyLength - counter] + secondViewCopy[secondViewCopyLength - counter] + c[0];\r\n break;\r\n default:\r\n value = firstViewCopy[firstViewCopyLength - counter] + c[0];\r\n }\r\n c[0] = value / 10;\r\n switch (true) {\r\n case (counter >= firstViewCopy.length):\r\n firstViewCopy = pvutils.utilConcatView(new Uint8Array([value % 10]), firstViewCopy);\r\n break;\r\n default:\r\n firstViewCopy[firstViewCopyLength - counter] = value % 10;\r\n }\r\n }\r\n if (c[0] > 0)\r\n firstViewCopy = pvutils.utilConcatView(c, firstViewCopy);\r\n return firstViewCopy;\r\n}\r\nfunction power2(n) {\r\n if (n >= powers2.length) {\r\n for (let p = powers2.length; p <= n; p++) {\r\n const c = new Uint8Array([0]);\r\n let digits = (powers2[p - 1]).slice(0);\r\n for (let i = (digits.length - 1); i >= 0; i--) {\r\n const newValue = new Uint8Array([(digits[i] << 1) + c[0]]);\r\n c[0] = newValue[0] / 10;\r\n digits[i] = newValue[0] % 10;\r\n }\r\n if (c[0] > 0)\r\n digits = pvutils.utilConcatView(c, digits);\r\n powers2.push(digits);\r\n }\r\n }\r\n return powers2[n];\r\n}\r\nfunction viewSub(first, second) {\r\n let b = 0;\r\n const firstView = new Uint8Array(first);\r\n const secondView = new Uint8Array(second);\r\n const firstViewCopy = firstView.slice(0);\r\n const firstViewCopyLength = firstViewCopy.length - 1;\r\n const secondViewCopy = secondView.slice(0);\r\n const secondViewCopyLength = secondViewCopy.length - 1;\r\n let value;\r\n let counter = 0;\r\n for (let i = secondViewCopyLength; i >= 0; i--, counter++) {\r\n value = firstViewCopy[firstViewCopyLength - counter] - secondViewCopy[secondViewCopyLength - counter] - b;\r\n switch (true) {\r\n case (value < 0):\r\n b = 1;\r\n firstViewCopy[firstViewCopyLength - counter] = value + 10;\r\n break;\r\n default:\r\n b = 0;\r\n firstViewCopy[firstViewCopyLength - counter] = value;\r\n }\r\n }\r\n if (b > 0) {\r\n for (let i = (firstViewCopyLength - secondViewCopyLength + 1); i >= 0; i--, counter++) {\r\n value = firstViewCopy[firstViewCopyLength - counter] - b;\r\n if (value < 0) {\r\n b = 1;\r\n firstViewCopy[firstViewCopyLength - counter] = value + 10;\r\n }\r\n else {\r\n b = 0;\r\n firstViewCopy[firstViewCopyLength - counter] = value;\r\n break;\r\n }\r\n }\r\n }\r\n return firstViewCopy.slice();\r\n}\r\nclass LocalIntegerValueBlock extends HexBlock(ValueBlock) {\r\n constructor({ value, ...parameters } = {}) {\r\n super(parameters);\r\n this._valueDec = 0;\r\n if (parameters.valueHex) {\r\n this.setValueHex();\r\n }\r\n if (value !== undefined) {\r\n this.valueDec = value;\r\n }\r\n }\r\n setValueHex() {\r\n if (this.valueHexView.length >= 4) {\r\n this.warnings.push(\"Too big Integer for decoding, hex only\");\r\n this.isHexOnly = true;\r\n this._valueDec = 0;\r\n }\r\n else {\r\n this.isHexOnly = false;\r\n if (this.valueHexView.length > 0) {\r\n this._valueDec = pvutils.utilDecodeTC.call(this);\r\n }\r\n }\r\n }\r\n set valueDec(v) {\r\n this._valueDec = v;\r\n this.isHexOnly = false;\r\n this.valueHexView = new Uint8Array(pvutils.utilEncodeTC(v));\r\n }\r\n get valueDec() {\r\n return this._valueDec;\r\n }\r\n fromDER(inputBuffer, inputOffset, inputLength, expectedLength = 0) {\r\n const offset = this.fromBER(inputBuffer, inputOffset, inputLength);\r\n if (offset === -1)\r\n return offset;\r\n const view = this.valueHexView;\r\n if ((view[0] === 0x00) && ((view[1] & 0x80) !== 0)) {\r\n this.valueHexView = view.subarray(1);\r\n }\r\n else {\r\n if (expectedLength !== 0) {\r\n if (view.length < expectedLength) {\r\n if ((expectedLength - view.length) > 1)\r\n expectedLength = view.length + 1;\r\n this.valueHexView = view.subarray(expectedLength - view.length);\r\n }\r\n }\r\n }\r\n return offset;\r\n }\r\n toDER(sizeOnly = false) {\r\n const view = this.valueHexView;\r\n switch (true) {\r\n case ((view[0] & 0x80) !== 0):\r\n {\r\n const updatedView = new Uint8Array(this.valueHexView.length + 1);\r\n updatedView[0] = 0x00;\r\n updatedView.set(view, 1);\r\n this.valueHexView = updatedView;\r\n }\r\n break;\r\n case ((view[0] === 0x00) && ((view[1] & 0x80) === 0)):\r\n {\r\n this.valueHexView = this.valueHexView.subarray(1);\r\n }\r\n break;\r\n }\r\n return this.toBER(sizeOnly);\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n const resultOffset = super.fromBER(inputBuffer, inputOffset, inputLength);\r\n if (resultOffset === -1) {\r\n return resultOffset;\r\n }\r\n this.setValueHex();\r\n return resultOffset;\r\n }\r\n toBER(sizeOnly) {\r\n return sizeOnly\r\n ? new ArrayBuffer(this.valueHexView.length)\r\n : this.valueHexView.slice().buffer;\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n valueDec: this.valueDec,\r\n };\r\n }\r\n toString() {\r\n const firstBit = (this.valueHexView.length * 8) - 1;\r\n let digits = new Uint8Array((this.valueHexView.length * 8) / 3);\r\n let bitNumber = 0;\r\n let currentByte;\r\n const asn1View = this.valueHexView;\r\n let result = \"\";\r\n let flag = false;\r\n for (let byteNumber = (asn1View.byteLength - 1); byteNumber >= 0; byteNumber--) {\r\n currentByte = asn1View[byteNumber];\r\n for (let i = 0; i < 8; i++) {\r\n if ((currentByte & 1) === 1) {\r\n switch (bitNumber) {\r\n case firstBit:\r\n digits = viewSub(power2(bitNumber), digits);\r\n result = \"-\";\r\n break;\r\n default:\r\n digits = viewAdd(digits, power2(bitNumber));\r\n }\r\n }\r\n bitNumber++;\r\n currentByte >>= 1;\r\n }\r\n }\r\n for (let i = 0; i < digits.length; i++) {\r\n if (digits[i])\r\n flag = true;\r\n if (flag)\r\n result += digitsString.charAt(digits[i]);\r\n }\r\n if (flag === false)\r\n result += digitsString.charAt(0);\r\n return result;\r\n }\r\n}\r\n_a$p = LocalIntegerValueBlock;\r\nLocalIntegerValueBlock.NAME = \"IntegerValueBlock\";\r\n(() => {\r\n Object.defineProperty(_a$p.prototype, \"valueHex\", {\r\n set: function (v) {\r\n this.valueHexView = new Uint8Array(v);\r\n this.setValueHex();\r\n },\r\n get: function () {\r\n return this.valueHexView.slice().buffer;\r\n },\r\n });\r\n})();\n\nvar _a$o;\r\nclass Integer extends BaseBlock {\r\n constructor(parameters = {}) {\r\n super(parameters, LocalIntegerValueBlock);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 2;\r\n }\r\n toBigInt() {\r\n assertBigInt();\r\n return BigInt(this.valueBlock.toString());\r\n }\r\n static fromBigInt(value) {\r\n assertBigInt();\r\n const bigIntValue = BigInt(value);\r\n const writer = new ViewWriter();\r\n const hex = bigIntValue.toString(16).replace(/^-/, \"\");\r\n const view = new Uint8Array(pvtsutils.Convert.FromHex(hex));\r\n if (bigIntValue < 0) {\r\n const first = new Uint8Array(view.length + (view[0] & 0x80 ? 1 : 0));\r\n first[0] |= 0x80;\r\n const firstInt = BigInt(`0x${pvtsutils.Convert.ToHex(first)}`);\r\n const secondInt = firstInt + bigIntValue;\r\n const second = pvtsutils.BufferSourceConverter.toUint8Array(pvtsutils.Convert.FromHex(secondInt.toString(16)));\r\n second[0] |= 0x80;\r\n writer.write(second);\r\n }\r\n else {\r\n if (view[0] & 0x80) {\r\n writer.write(new Uint8Array([0]));\r\n }\r\n writer.write(view);\r\n }\r\n const res = new Integer({\r\n valueHex: writer.final(),\r\n });\r\n return res;\r\n }\r\n convertToDER() {\r\n const integer = new Integer({ valueHex: this.valueBlock.valueHexView });\r\n integer.valueBlock.toDER();\r\n return integer;\r\n }\r\n convertFromDER() {\r\n return new Integer({\r\n valueHex: this.valueBlock.valueHexView[0] === 0\r\n ? this.valueBlock.valueHexView.subarray(1)\r\n : this.valueBlock.valueHexView,\r\n });\r\n }\r\n onAsciiEncoding() {\r\n return `${this.constructor.NAME} : ${this.valueBlock.toString()}`;\r\n }\r\n}\r\n_a$o = Integer;\r\n(() => {\r\n typeStore.Integer = _a$o;\r\n})();\r\nInteger.NAME = \"INTEGER\";\n\nvar _a$n;\r\nclass Enumerated extends Integer {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 10;\r\n }\r\n}\r\n_a$n = Enumerated;\r\n(() => {\r\n typeStore.Enumerated = _a$n;\r\n})();\r\nEnumerated.NAME = \"ENUMERATED\";\n\nclass LocalSidValueBlock extends HexBlock(ValueBlock) {\r\n constructor({ valueDec = -1, isFirstSid = false, ...parameters } = {}) {\r\n super(parameters);\r\n this.valueDec = valueDec;\r\n this.isFirstSid = isFirstSid;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n if (!inputLength) {\r\n return inputOffset;\r\n }\r\n const inputView = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer);\r\n if (!checkBufferParams(this, inputView, inputOffset, inputLength)) {\r\n return -1;\r\n }\r\n const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength);\r\n this.valueHexView = new Uint8Array(inputLength);\r\n for (let i = 0; i < inputLength; i++) {\r\n this.valueHexView[i] = intBuffer[i] & 0x7F;\r\n this.blockLength++;\r\n if ((intBuffer[i] & 0x80) === 0x00)\r\n break;\r\n }\r\n const tempView = new Uint8Array(this.blockLength);\r\n for (let i = 0; i < this.blockLength; i++) {\r\n tempView[i] = this.valueHexView[i];\r\n }\r\n this.valueHexView = tempView;\r\n if ((intBuffer[this.blockLength - 1] & 0x80) !== 0x00) {\r\n this.error = \"End of input reached before message was fully decoded\";\r\n return -1;\r\n }\r\n if (this.valueHexView[0] === 0x00)\r\n this.warnings.push(\"Needlessly long format of SID encoding\");\r\n if (this.blockLength <= 8)\r\n this.valueDec = pvutils.utilFromBase(this.valueHexView, 7);\r\n else {\r\n this.isHexOnly = true;\r\n this.warnings.push(\"Too big SID for decoding, hex only\");\r\n }\r\n return (inputOffset + this.blockLength);\r\n }\r\n set valueBigInt(value) {\r\n assertBigInt();\r\n let bits = BigInt(value).toString(2);\r\n while (bits.length % 7) {\r\n bits = \"0\" + bits;\r\n }\r\n const bytes = new Uint8Array(bits.length / 7);\r\n for (let i = 0; i < bytes.length; i++) {\r\n bytes[i] = parseInt(bits.slice(i * 7, i * 7 + 7), 2) + (i + 1 < bytes.length ? 0x80 : 0);\r\n }\r\n this.fromBER(bytes.buffer, 0, bytes.length);\r\n }\r\n toBER(sizeOnly) {\r\n if (this.isHexOnly) {\r\n if (sizeOnly)\r\n return (new ArrayBuffer(this.valueHexView.byteLength));\r\n const curView = this.valueHexView;\r\n const retView = new Uint8Array(this.blockLength);\r\n for (let i = 0; i < (this.blockLength - 1); i++)\r\n retView[i] = curView[i] | 0x80;\r\n retView[this.blockLength - 1] = curView[this.blockLength - 1];\r\n return retView.buffer;\r\n }\r\n const encodedBuf = pvutils.utilToBase(this.valueDec, 7);\r\n if (encodedBuf.byteLength === 0) {\r\n this.error = \"Error during encoding SID value\";\r\n return EMPTY_BUFFER;\r\n }\r\n const retView = new Uint8Array(encodedBuf.byteLength);\r\n if (!sizeOnly) {\r\n const encodedView = new Uint8Array(encodedBuf);\r\n const len = encodedBuf.byteLength - 1;\r\n for (let i = 0; i < len; i++)\r\n retView[i] = encodedView[i] | 0x80;\r\n retView[len] = encodedView[len];\r\n }\r\n return retView;\r\n }\r\n toString() {\r\n let result = \"\";\r\n if (this.isHexOnly)\r\n result = pvtsutils.Convert.ToHex(this.valueHexView);\r\n else {\r\n if (this.isFirstSid) {\r\n let sidValue = this.valueDec;\r\n if (this.valueDec <= 39)\r\n result = \"0.\";\r\n else {\r\n if (this.valueDec <= 79) {\r\n result = \"1.\";\r\n sidValue -= 40;\r\n }\r\n else {\r\n result = \"2.\";\r\n sidValue -= 80;\r\n }\r\n }\r\n result += sidValue.toString();\r\n }\r\n else\r\n result = this.valueDec.toString();\r\n }\r\n return result;\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n valueDec: this.valueDec,\r\n isFirstSid: this.isFirstSid,\r\n };\r\n }\r\n}\r\nLocalSidValueBlock.NAME = \"sidBlock\";\n\nclass LocalObjectIdentifierValueBlock extends ValueBlock {\r\n constructor({ value = EMPTY_STRING, ...parameters } = {}) {\r\n super(parameters);\r\n this.value = [];\r\n if (value) {\r\n this.fromString(value);\r\n }\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n let resultOffset = inputOffset;\r\n while (inputLength > 0) {\r\n const sidBlock = new LocalSidValueBlock();\r\n resultOffset = sidBlock.fromBER(inputBuffer, resultOffset, inputLength);\r\n if (resultOffset === -1) {\r\n this.blockLength = 0;\r\n this.error = sidBlock.error;\r\n return resultOffset;\r\n }\r\n if (this.value.length === 0)\r\n sidBlock.isFirstSid = true;\r\n this.blockLength += sidBlock.blockLength;\r\n inputLength -= sidBlock.blockLength;\r\n this.value.push(sidBlock);\r\n }\r\n return resultOffset;\r\n }\r\n toBER(sizeOnly) {\r\n const retBuffers = [];\r\n for (let i = 0; i < this.value.length; i++) {\r\n const valueBuf = this.value[i].toBER(sizeOnly);\r\n if (valueBuf.byteLength === 0) {\r\n this.error = this.value[i].error;\r\n return EMPTY_BUFFER;\r\n }\r\n retBuffers.push(valueBuf);\r\n }\r\n return concat(retBuffers);\r\n }\r\n fromString(string) {\r\n this.value = [];\r\n let pos1 = 0;\r\n let pos2 = 0;\r\n let sid = \"\";\r\n let flag = false;\r\n do {\r\n pos2 = string.indexOf(\".\", pos1);\r\n if (pos2 === -1)\r\n sid = string.substring(pos1);\r\n else\r\n sid = string.substring(pos1, pos2);\r\n pos1 = pos2 + 1;\r\n if (flag) {\r\n const sidBlock = this.value[0];\r\n let plus = 0;\r\n switch (sidBlock.valueDec) {\r\n case 0:\r\n break;\r\n case 1:\r\n plus = 40;\r\n break;\r\n case 2:\r\n plus = 80;\r\n break;\r\n default:\r\n this.value = [];\r\n return;\r\n }\r\n const parsedSID = parseInt(sid, 10);\r\n if (isNaN(parsedSID))\r\n return;\r\n sidBlock.valueDec = parsedSID + plus;\r\n flag = false;\r\n }\r\n else {\r\n const sidBlock = new LocalSidValueBlock();\r\n if (sid > Number.MAX_SAFE_INTEGER) {\r\n assertBigInt();\r\n const sidValue = BigInt(sid);\r\n sidBlock.valueBigInt = sidValue;\r\n }\r\n else {\r\n sidBlock.valueDec = parseInt(sid, 10);\r\n if (isNaN(sidBlock.valueDec))\r\n return;\r\n }\r\n if (!this.value.length) {\r\n sidBlock.isFirstSid = true;\r\n flag = true;\r\n }\r\n this.value.push(sidBlock);\r\n }\r\n } while (pos2 !== -1);\r\n }\r\n toString() {\r\n let result = \"\";\r\n let isHexOnly = false;\r\n for (let i = 0; i < this.value.length; i++) {\r\n isHexOnly = this.value[i].isHexOnly;\r\n let sidStr = this.value[i].toString();\r\n if (i !== 0)\r\n result = `${result}.`;\r\n if (isHexOnly) {\r\n sidStr = `{${sidStr}}`;\r\n if (this.value[i].isFirstSid)\r\n result = `2.{${sidStr} - 80}`;\r\n else\r\n result += sidStr;\r\n }\r\n else\r\n result += sidStr;\r\n }\r\n return result;\r\n }\r\n toJSON() {\r\n const object = {\r\n ...super.toJSON(),\r\n value: this.toString(),\r\n sidArray: [],\r\n };\r\n for (let i = 0; i < this.value.length; i++) {\r\n object.sidArray.push(this.value[i].toJSON());\r\n }\r\n return object;\r\n }\r\n}\r\nLocalObjectIdentifierValueBlock.NAME = \"ObjectIdentifierValueBlock\";\n\nvar _a$m;\r\nclass ObjectIdentifier extends BaseBlock {\r\n constructor(parameters = {}) {\r\n super(parameters, LocalObjectIdentifierValueBlock);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 6;\r\n }\r\n getValue() {\r\n return this.valueBlock.toString();\r\n }\r\n setValue(value) {\r\n this.valueBlock.fromString(value);\r\n }\r\n onAsciiEncoding() {\r\n return `${this.constructor.NAME} : ${this.valueBlock.toString() || \"empty\"}`;\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n value: this.getValue(),\r\n };\r\n }\r\n}\r\n_a$m = ObjectIdentifier;\r\n(() => {\r\n typeStore.ObjectIdentifier = _a$m;\r\n})();\r\nObjectIdentifier.NAME = \"OBJECT IDENTIFIER\";\n\nclass LocalRelativeSidValueBlock extends HexBlock(LocalBaseBlock) {\r\n constructor({ valueDec = 0, ...parameters } = {}) {\r\n super(parameters);\r\n this.valueDec = valueDec;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n if (inputLength === 0)\r\n return inputOffset;\r\n const inputView = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer);\r\n if (!checkBufferParams(this, inputView, inputOffset, inputLength))\r\n return -1;\r\n const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength);\r\n this.valueHexView = new Uint8Array(inputLength);\r\n for (let i = 0; i < inputLength; i++) {\r\n this.valueHexView[i] = intBuffer[i] & 0x7F;\r\n this.blockLength++;\r\n if ((intBuffer[i] & 0x80) === 0x00)\r\n break;\r\n }\r\n const tempView = new Uint8Array(this.blockLength);\r\n for (let i = 0; i < this.blockLength; i++)\r\n tempView[i] = this.valueHexView[i];\r\n this.valueHexView = tempView;\r\n if ((intBuffer[this.blockLength - 1] & 0x80) !== 0x00) {\r\n this.error = \"End of input reached before message was fully decoded\";\r\n return -1;\r\n }\r\n if (this.valueHexView[0] === 0x00)\r\n this.warnings.push(\"Needlessly long format of SID encoding\");\r\n if (this.blockLength <= 8)\r\n this.valueDec = pvutils.utilFromBase(this.valueHexView, 7);\r\n else {\r\n this.isHexOnly = true;\r\n this.warnings.push(\"Too big SID for decoding, hex only\");\r\n }\r\n return (inputOffset + this.blockLength);\r\n }\r\n toBER(sizeOnly) {\r\n if (this.isHexOnly) {\r\n if (sizeOnly)\r\n return (new ArrayBuffer(this.valueHexView.byteLength));\r\n const curView = this.valueHexView;\r\n const retView = new Uint8Array(this.blockLength);\r\n for (let i = 0; i < (this.blockLength - 1); i++)\r\n retView[i] = curView[i] | 0x80;\r\n retView[this.blockLength - 1] = curView[this.blockLength - 1];\r\n return retView.buffer;\r\n }\r\n const encodedBuf = pvutils.utilToBase(this.valueDec, 7);\r\n if (encodedBuf.byteLength === 0) {\r\n this.error = \"Error during encoding SID value\";\r\n return EMPTY_BUFFER;\r\n }\r\n const retView = new Uint8Array(encodedBuf.byteLength);\r\n if (!sizeOnly) {\r\n const encodedView = new Uint8Array(encodedBuf);\r\n const len = encodedBuf.byteLength - 1;\r\n for (let i = 0; i < len; i++)\r\n retView[i] = encodedView[i] | 0x80;\r\n retView[len] = encodedView[len];\r\n }\r\n return retView.buffer;\r\n }\r\n toString() {\r\n let result = \"\";\r\n if (this.isHexOnly)\r\n result = pvtsutils.Convert.ToHex(this.valueHexView);\r\n else {\r\n result = this.valueDec.toString();\r\n }\r\n return result;\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n valueDec: this.valueDec,\r\n };\r\n }\r\n}\r\nLocalRelativeSidValueBlock.NAME = \"relativeSidBlock\";\n\nclass LocalRelativeObjectIdentifierValueBlock extends ValueBlock {\r\n constructor({ value = EMPTY_STRING, ...parameters } = {}) {\r\n super(parameters);\r\n this.value = [];\r\n if (value) {\r\n this.fromString(value);\r\n }\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n let resultOffset = inputOffset;\r\n while (inputLength > 0) {\r\n const sidBlock = new LocalRelativeSidValueBlock();\r\n resultOffset = sidBlock.fromBER(inputBuffer, resultOffset, inputLength);\r\n if (resultOffset === -1) {\r\n this.blockLength = 0;\r\n this.error = sidBlock.error;\r\n return resultOffset;\r\n }\r\n this.blockLength += sidBlock.blockLength;\r\n inputLength -= sidBlock.blockLength;\r\n this.value.push(sidBlock);\r\n }\r\n return resultOffset;\r\n }\r\n toBER(sizeOnly, writer) {\r\n const retBuffers = [];\r\n for (let i = 0; i < this.value.length; i++) {\r\n const valueBuf = this.value[i].toBER(sizeOnly);\r\n if (valueBuf.byteLength === 0) {\r\n this.error = this.value[i].error;\r\n return EMPTY_BUFFER;\r\n }\r\n retBuffers.push(valueBuf);\r\n }\r\n return concat(retBuffers);\r\n }\r\n fromString(string) {\r\n this.value = [];\r\n let pos1 = 0;\r\n let pos2 = 0;\r\n let sid = \"\";\r\n do {\r\n pos2 = string.indexOf(\".\", pos1);\r\n if (pos2 === -1)\r\n sid = string.substring(pos1);\r\n else\r\n sid = string.substring(pos1, pos2);\r\n pos1 = pos2 + 1;\r\n const sidBlock = new LocalRelativeSidValueBlock();\r\n sidBlock.valueDec = parseInt(sid, 10);\r\n if (isNaN(sidBlock.valueDec))\r\n return true;\r\n this.value.push(sidBlock);\r\n } while (pos2 !== -1);\r\n return true;\r\n }\r\n toString() {\r\n let result = \"\";\r\n let isHexOnly = false;\r\n for (let i = 0; i < this.value.length; i++) {\r\n isHexOnly = this.value[i].isHexOnly;\r\n let sidStr = this.value[i].toString();\r\n if (i !== 0)\r\n result = `${result}.`;\r\n if (isHexOnly) {\r\n sidStr = `{${sidStr}}`;\r\n result += sidStr;\r\n }\r\n else\r\n result += sidStr;\r\n }\r\n return result;\r\n }\r\n toJSON() {\r\n const object = {\r\n ...super.toJSON(),\r\n value: this.toString(),\r\n sidArray: [],\r\n };\r\n for (let i = 0; i < this.value.length; i++)\r\n object.sidArray.push(this.value[i].toJSON());\r\n return object;\r\n }\r\n}\r\nLocalRelativeObjectIdentifierValueBlock.NAME = \"RelativeObjectIdentifierValueBlock\";\n\nvar _a$l;\r\nclass RelativeObjectIdentifier extends BaseBlock {\r\n constructor(parameters = {}) {\r\n super(parameters, LocalRelativeObjectIdentifierValueBlock);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 13;\r\n }\r\n getValue() {\r\n return this.valueBlock.toString();\r\n }\r\n setValue(value) {\r\n this.valueBlock.fromString(value);\r\n }\r\n onAsciiEncoding() {\r\n return `${this.constructor.NAME} : ${this.valueBlock.toString() || \"empty\"}`;\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n value: this.getValue(),\r\n };\r\n }\r\n}\r\n_a$l = RelativeObjectIdentifier;\r\n(() => {\r\n typeStore.RelativeObjectIdentifier = _a$l;\r\n})();\r\nRelativeObjectIdentifier.NAME = \"RelativeObjectIdentifier\";\n\nvar _a$k;\r\nclass Sequence extends Constructed {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 16;\r\n }\r\n}\r\n_a$k = Sequence;\r\n(() => {\r\n typeStore.Sequence = _a$k;\r\n})();\r\nSequence.NAME = \"SEQUENCE\";\n\nvar _a$j;\r\nclass Set extends Constructed {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 17;\r\n }\r\n}\r\n_a$j = Set;\r\n(() => {\r\n typeStore.Set = _a$j;\r\n})();\r\nSet.NAME = \"SET\";\n\nclass LocalStringValueBlock extends HexBlock(ValueBlock) {\r\n constructor({ ...parameters } = {}) {\r\n super(parameters);\r\n this.isHexOnly = true;\r\n this.value = EMPTY_STRING;\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n value: this.value,\r\n };\r\n }\r\n}\r\nLocalStringValueBlock.NAME = \"StringValueBlock\";\n\nclass LocalSimpleStringValueBlock extends LocalStringValueBlock {\r\n}\r\nLocalSimpleStringValueBlock.NAME = \"SimpleStringValueBlock\";\n\nclass LocalSimpleStringBlock extends BaseStringBlock {\r\n constructor({ ...parameters } = {}) {\r\n super(parameters, LocalSimpleStringValueBlock);\r\n }\r\n fromBuffer(inputBuffer) {\r\n this.valueBlock.value = String.fromCharCode.apply(null, pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer));\r\n }\r\n fromString(inputString) {\r\n const strLen = inputString.length;\r\n const view = this.valueBlock.valueHexView = new Uint8Array(strLen);\r\n for (let i = 0; i < strLen; i++)\r\n view[i] = inputString.charCodeAt(i);\r\n this.valueBlock.value = inputString;\r\n }\r\n}\r\nLocalSimpleStringBlock.NAME = \"SIMPLE STRING\";\n\nclass LocalUtf8StringValueBlock extends LocalSimpleStringBlock {\r\n fromBuffer(inputBuffer) {\r\n this.valueBlock.valueHexView = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer);\r\n try {\r\n this.valueBlock.value = pvtsutils.Convert.ToUtf8String(inputBuffer);\r\n }\r\n catch (ex) {\r\n this.warnings.push(`Error during \"decodeURIComponent\": ${ex}, using raw string`);\r\n this.valueBlock.value = pvtsutils.Convert.ToBinary(inputBuffer);\r\n }\r\n }\r\n fromString(inputString) {\r\n this.valueBlock.valueHexView = new Uint8Array(pvtsutils.Convert.FromUtf8String(inputString));\r\n this.valueBlock.value = inputString;\r\n }\r\n}\r\nLocalUtf8StringValueBlock.NAME = \"Utf8StringValueBlock\";\n\nvar _a$i;\r\nclass Utf8String extends LocalUtf8StringValueBlock {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 12;\r\n }\r\n}\r\n_a$i = Utf8String;\r\n(() => {\r\n typeStore.Utf8String = _a$i;\r\n})();\r\nUtf8String.NAME = \"UTF8String\";\n\nclass LocalBmpStringValueBlock extends LocalSimpleStringBlock {\r\n fromBuffer(inputBuffer) {\r\n this.valueBlock.value = pvtsutils.Convert.ToUtf16String(inputBuffer);\r\n this.valueBlock.valueHexView = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer);\r\n }\r\n fromString(inputString) {\r\n this.valueBlock.value = inputString;\r\n this.valueBlock.valueHexView = new Uint8Array(pvtsutils.Convert.FromUtf16String(inputString));\r\n }\r\n}\r\nLocalBmpStringValueBlock.NAME = \"BmpStringValueBlock\";\n\nvar _a$h;\r\nclass BmpString extends LocalBmpStringValueBlock {\r\n constructor({ ...parameters } = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 30;\r\n }\r\n}\r\n_a$h = BmpString;\r\n(() => {\r\n typeStore.BmpString = _a$h;\r\n})();\r\nBmpString.NAME = \"BMPString\";\n\nclass LocalUniversalStringValueBlock extends LocalSimpleStringBlock {\r\n fromBuffer(inputBuffer) {\r\n const copyBuffer = ArrayBuffer.isView(inputBuffer) ? inputBuffer.slice().buffer : inputBuffer.slice(0);\r\n const valueView = new Uint8Array(copyBuffer);\r\n for (let i = 0; i < valueView.length; i += 4) {\r\n valueView[i] = valueView[i + 3];\r\n valueView[i + 1] = valueView[i + 2];\r\n valueView[i + 2] = 0x00;\r\n valueView[i + 3] = 0x00;\r\n }\r\n this.valueBlock.value = String.fromCharCode.apply(null, new Uint32Array(copyBuffer));\r\n }\r\n fromString(inputString) {\r\n const strLength = inputString.length;\r\n const valueHexView = this.valueBlock.valueHexView = new Uint8Array(strLength * 4);\r\n for (let i = 0; i < strLength; i++) {\r\n const codeBuf = pvutils.utilToBase(inputString.charCodeAt(i), 8);\r\n const codeView = new Uint8Array(codeBuf);\r\n if (codeView.length > 4)\r\n continue;\r\n const dif = 4 - codeView.length;\r\n for (let j = (codeView.length - 1); j >= 0; j--)\r\n valueHexView[i * 4 + j + dif] = codeView[j];\r\n }\r\n this.valueBlock.value = inputString;\r\n }\r\n}\r\nLocalUniversalStringValueBlock.NAME = \"UniversalStringValueBlock\";\n\nvar _a$g;\r\nclass UniversalString extends LocalUniversalStringValueBlock {\r\n constructor({ ...parameters } = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 28;\r\n }\r\n}\r\n_a$g = UniversalString;\r\n(() => {\r\n typeStore.UniversalString = _a$g;\r\n})();\r\nUniversalString.NAME = \"UniversalString\";\n\nvar _a$f;\r\nclass NumericString extends LocalSimpleStringBlock {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 18;\r\n }\r\n}\r\n_a$f = NumericString;\r\n(() => {\r\n typeStore.NumericString = _a$f;\r\n})();\r\nNumericString.NAME = \"NumericString\";\n\nvar _a$e;\r\nclass PrintableString extends LocalSimpleStringBlock {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 19;\r\n }\r\n}\r\n_a$e = PrintableString;\r\n(() => {\r\n typeStore.PrintableString = _a$e;\r\n})();\r\nPrintableString.NAME = \"PrintableString\";\n\nvar _a$d;\r\nclass TeletexString extends LocalSimpleStringBlock {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 20;\r\n }\r\n}\r\n_a$d = TeletexString;\r\n(() => {\r\n typeStore.TeletexString = _a$d;\r\n})();\r\nTeletexString.NAME = \"TeletexString\";\n\nvar _a$c;\r\nclass VideotexString extends LocalSimpleStringBlock {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 21;\r\n }\r\n}\r\n_a$c = VideotexString;\r\n(() => {\r\n typeStore.VideotexString = _a$c;\r\n})();\r\nVideotexString.NAME = \"VideotexString\";\n\nvar _a$b;\r\nclass IA5String extends LocalSimpleStringBlock {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 22;\r\n }\r\n}\r\n_a$b = IA5String;\r\n(() => {\r\n typeStore.IA5String = _a$b;\r\n})();\r\nIA5String.NAME = \"IA5String\";\n\nvar _a$a;\r\nclass GraphicString extends LocalSimpleStringBlock {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 25;\r\n }\r\n}\r\n_a$a = GraphicString;\r\n(() => {\r\n typeStore.GraphicString = _a$a;\r\n})();\r\nGraphicString.NAME = \"GraphicString\";\n\nvar _a$9;\r\nclass VisibleString extends LocalSimpleStringBlock {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 26;\r\n }\r\n}\r\n_a$9 = VisibleString;\r\n(() => {\r\n typeStore.VisibleString = _a$9;\r\n})();\r\nVisibleString.NAME = \"VisibleString\";\n\nvar _a$8;\r\nclass GeneralString extends LocalSimpleStringBlock {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 27;\r\n }\r\n}\r\n_a$8 = GeneralString;\r\n(() => {\r\n typeStore.GeneralString = _a$8;\r\n})();\r\nGeneralString.NAME = \"GeneralString\";\n\nvar _a$7;\r\nclass CharacterString extends LocalSimpleStringBlock {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 29;\r\n }\r\n}\r\n_a$7 = CharacterString;\r\n(() => {\r\n typeStore.CharacterString = _a$7;\r\n})();\r\nCharacterString.NAME = \"CharacterString\";\n\nvar _a$6;\r\nclass UTCTime extends VisibleString {\r\n constructor({ value, valueDate, ...parameters } = {}) {\r\n super(parameters);\r\n this.year = 0;\r\n this.month = 0;\r\n this.day = 0;\r\n this.hour = 0;\r\n this.minute = 0;\r\n this.second = 0;\r\n if (value) {\r\n this.fromString(value);\r\n this.valueBlock.valueHexView = new Uint8Array(value.length);\r\n for (let i = 0; i < value.length; i++)\r\n this.valueBlock.valueHexView[i] = value.charCodeAt(i);\r\n }\r\n if (valueDate) {\r\n this.fromDate(valueDate);\r\n this.valueBlock.valueHexView = new Uint8Array(this.toBuffer());\r\n }\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 23;\r\n }\r\n fromBuffer(inputBuffer) {\r\n this.fromString(String.fromCharCode.apply(null, pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer)));\r\n }\r\n toBuffer() {\r\n const str = this.toString();\r\n const buffer = new ArrayBuffer(str.length);\r\n const view = new Uint8Array(buffer);\r\n for (let i = 0; i < str.length; i++)\r\n view[i] = str.charCodeAt(i);\r\n return buffer;\r\n }\r\n fromDate(inputDate) {\r\n this.year = inputDate.getUTCFullYear();\r\n this.month = inputDate.getUTCMonth() + 1;\r\n this.day = inputDate.getUTCDate();\r\n this.hour = inputDate.getUTCHours();\r\n this.minute = inputDate.getUTCMinutes();\r\n this.second = inputDate.getUTCSeconds();\r\n }\r\n toDate() {\r\n return (new Date(Date.UTC(this.year, this.month - 1, this.day, this.hour, this.minute, this.second)));\r\n }\r\n fromString(inputString) {\r\n const parser = /(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})Z/ig;\r\n const parserArray = parser.exec(inputString);\r\n if (parserArray === null) {\r\n this.error = \"Wrong input string for conversion\";\r\n return;\r\n }\r\n const year = parseInt(parserArray[1], 10);\r\n if (year >= 50)\r\n this.year = 1900 + year;\r\n else\r\n this.year = 2000 + year;\r\n this.month = parseInt(parserArray[2], 10);\r\n this.day = parseInt(parserArray[3], 10);\r\n this.hour = parseInt(parserArray[4], 10);\r\n this.minute = parseInt(parserArray[5], 10);\r\n this.second = parseInt(parserArray[6], 10);\r\n }\r\n toString(encoding = \"iso\") {\r\n if (encoding === \"iso\") {\r\n const outputArray = new Array(7);\r\n outputArray[0] = pvutils.padNumber(((this.year < 2000) ? (this.year - 1900) : (this.year - 2000)), 2);\r\n outputArray[1] = pvutils.padNumber(this.month, 2);\r\n outputArray[2] = pvutils.padNumber(this.day, 2);\r\n outputArray[3] = pvutils.padNumber(this.hour, 2);\r\n outputArray[4] = pvutils.padNumber(this.minute, 2);\r\n outputArray[5] = pvutils.padNumber(this.second, 2);\r\n outputArray[6] = \"Z\";\r\n return outputArray.join(\"\");\r\n }\r\n return super.toString(encoding);\r\n }\r\n onAsciiEncoding() {\r\n return `${this.constructor.NAME} : ${this.toDate().toISOString()}`;\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n year: this.year,\r\n month: this.month,\r\n day: this.day,\r\n hour: this.hour,\r\n minute: this.minute,\r\n second: this.second,\r\n };\r\n }\r\n}\r\n_a$6 = UTCTime;\r\n(() => {\r\n typeStore.UTCTime = _a$6;\r\n})();\r\nUTCTime.NAME = \"UTCTime\";\n\nvar _a$5;\r\nclass GeneralizedTime extends UTCTime {\r\n constructor(parameters = {}) {\r\n var _b;\r\n super(parameters);\r\n (_b = this.millisecond) !== null && _b !== void 0 ? _b : (this.millisecond = 0);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 24;\r\n }\r\n fromDate(inputDate) {\r\n super.fromDate(inputDate);\r\n this.millisecond = inputDate.getUTCMilliseconds();\r\n }\r\n toDate() {\r\n return (new Date(Date.UTC(this.year, this.month - 1, this.day, this.hour, this.minute, this.second, this.millisecond)));\r\n }\r\n fromString(inputString) {\r\n let isUTC = false;\r\n let timeString = \"\";\r\n let dateTimeString = \"\";\r\n let fractionPart = 0;\r\n let parser;\r\n let hourDifference = 0;\r\n let minuteDifference = 0;\r\n if (inputString[inputString.length - 1] === \"Z\") {\r\n timeString = inputString.substring(0, inputString.length - 1);\r\n isUTC = true;\r\n }\r\n else {\r\n const number = new Number(inputString[inputString.length - 1]);\r\n if (isNaN(number.valueOf()))\r\n throw new Error(\"Wrong input string for conversion\");\r\n timeString = inputString;\r\n }\r\n if (isUTC) {\r\n if (timeString.indexOf(\"+\") !== -1)\r\n throw new Error(\"Wrong input string for conversion\");\r\n if (timeString.indexOf(\"-\") !== -1)\r\n throw new Error(\"Wrong input string for conversion\");\r\n }\r\n else {\r\n let multiplier = 1;\r\n let differencePosition = timeString.indexOf(\"+\");\r\n let differenceString = \"\";\r\n if (differencePosition === -1) {\r\n differencePosition = timeString.indexOf(\"-\");\r\n multiplier = -1;\r\n }\r\n if (differencePosition !== -1) {\r\n differenceString = timeString.substring(differencePosition + 1);\r\n timeString = timeString.substring(0, differencePosition);\r\n if ((differenceString.length !== 2) && (differenceString.length !== 4))\r\n throw new Error(\"Wrong input string for conversion\");\r\n let number = parseInt(differenceString.substring(0, 2), 10);\r\n if (isNaN(number.valueOf()))\r\n throw new Error(\"Wrong input string for conversion\");\r\n hourDifference = multiplier * number;\r\n if (differenceString.length === 4) {\r\n number = parseInt(differenceString.substring(2, 4), 10);\r\n if (isNaN(number.valueOf()))\r\n throw new Error(\"Wrong input string for conversion\");\r\n minuteDifference = multiplier * number;\r\n }\r\n }\r\n }\r\n let fractionPointPosition = timeString.indexOf(\".\");\r\n if (fractionPointPosition === -1)\r\n fractionPointPosition = timeString.indexOf(\",\");\r\n if (fractionPointPosition !== -1) {\r\n const fractionPartCheck = new Number(`0${timeString.substring(fractionPointPosition)}`);\r\n if (isNaN(fractionPartCheck.valueOf()))\r\n throw new Error(\"Wrong input string for conversion\");\r\n fractionPart = fractionPartCheck.valueOf();\r\n dateTimeString = timeString.substring(0, fractionPointPosition);\r\n }\r\n else\r\n dateTimeString = timeString;\r\n switch (true) {\r\n case (dateTimeString.length === 8):\r\n parser = /(\\d{4})(\\d{2})(\\d{2})/ig;\r\n if (fractionPointPosition !== -1)\r\n throw new Error(\"Wrong input string for conversion\");\r\n break;\r\n case (dateTimeString.length === 10):\r\n parser = /(\\d{4})(\\d{2})(\\d{2})(\\d{2})/ig;\r\n if (fractionPointPosition !== -1) {\r\n let fractionResult = 60 * fractionPart;\r\n this.minute = Math.floor(fractionResult);\r\n fractionResult = 60 * (fractionResult - this.minute);\r\n this.second = Math.floor(fractionResult);\r\n fractionResult = 1000 * (fractionResult - this.second);\r\n this.millisecond = Math.floor(fractionResult);\r\n }\r\n break;\r\n case (dateTimeString.length === 12):\r\n parser = /(\\d{4})(\\d{2})(\\d{2})(\\d{2})(\\d{2})/ig;\r\n if (fractionPointPosition !== -1) {\r\n let fractionResult = 60 * fractionPart;\r\n this.second = Math.floor(fractionResult);\r\n fractionResult = 1000 * (fractionResult - this.second);\r\n this.millisecond = Math.floor(fractionResult);\r\n }\r\n break;\r\n case (dateTimeString.length === 14):\r\n parser = /(\\d{4})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})/ig;\r\n if (fractionPointPosition !== -1) {\r\n const fractionResult = 1000 * fractionPart;\r\n this.millisecond = Math.floor(fractionResult);\r\n }\r\n break;\r\n default:\r\n throw new Error(\"Wrong input string for conversion\");\r\n }\r\n const parserArray = parser.exec(dateTimeString);\r\n if (parserArray === null)\r\n throw new Error(\"Wrong input string for conversion\");\r\n for (let j = 1; j < parserArray.length; j++) {\r\n switch (j) {\r\n case 1:\r\n this.year = parseInt(parserArray[j], 10);\r\n break;\r\n case 2:\r\n this.month = parseInt(parserArray[j], 10);\r\n break;\r\n case 3:\r\n this.day = parseInt(parserArray[j], 10);\r\n break;\r\n case 4:\r\n this.hour = parseInt(parserArray[j], 10) + hourDifference;\r\n break;\r\n case 5:\r\n this.minute = parseInt(parserArray[j], 10) + minuteDifference;\r\n break;\r\n case 6:\r\n this.second = parseInt(parserArray[j], 10);\r\n break;\r\n default:\r\n throw new Error(\"Wrong input string for conversion\");\r\n }\r\n }\r\n if (isUTC === false) {\r\n const tempDate = new Date(this.year, this.month, this.day, this.hour, this.minute, this.second, this.millisecond);\r\n this.year = tempDate.getUTCFullYear();\r\n this.month = tempDate.getUTCMonth();\r\n this.day = tempDate.getUTCDay();\r\n this.hour = tempDate.getUTCHours();\r\n this.minute = tempDate.getUTCMinutes();\r\n this.second = tempDate.getUTCSeconds();\r\n this.millisecond = tempDate.getUTCMilliseconds();\r\n }\r\n }\r\n toString(encoding = \"iso\") {\r\n if (encoding === \"iso\") {\r\n const outputArray = [];\r\n outputArray.push(pvutils.padNumber(this.year, 4));\r\n outputArray.push(pvutils.padNumber(this.month, 2));\r\n outputArray.push(pvutils.padNumber(this.day, 2));\r\n outputArray.push(pvutils.padNumber(this.hour, 2));\r\n outputArray.push(pvutils.padNumber(this.minute, 2));\r\n outputArray.push(pvutils.padNumber(this.second, 2));\r\n if (this.millisecond !== 0) {\r\n outputArray.push(\".\");\r\n outputArray.push(pvutils.padNumber(this.millisecond, 3));\r\n }\r\n outputArray.push(\"Z\");\r\n return outputArray.join(\"\");\r\n }\r\n return super.toString(encoding);\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n millisecond: this.millisecond,\r\n };\r\n }\r\n}\r\n_a$5 = GeneralizedTime;\r\n(() => {\r\n typeStore.GeneralizedTime = _a$5;\r\n})();\r\nGeneralizedTime.NAME = \"GeneralizedTime\";\n\nvar _a$4;\r\nclass DATE extends Utf8String {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 31;\r\n }\r\n}\r\n_a$4 = DATE;\r\n(() => {\r\n typeStore.DATE = _a$4;\r\n})();\r\nDATE.NAME = \"DATE\";\n\nvar _a$3;\r\nclass TimeOfDay extends Utf8String {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 32;\r\n }\r\n}\r\n_a$3 = TimeOfDay;\r\n(() => {\r\n typeStore.TimeOfDay = _a$3;\r\n})();\r\nTimeOfDay.NAME = \"TimeOfDay\";\n\nvar _a$2;\r\nclass DateTime extends Utf8String {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 33;\r\n }\r\n}\r\n_a$2 = DateTime;\r\n(() => {\r\n typeStore.DateTime = _a$2;\r\n})();\r\nDateTime.NAME = \"DateTime\";\n\nvar _a$1;\r\nclass Duration extends Utf8String {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 34;\r\n }\r\n}\r\n_a$1 = Duration;\r\n(() => {\r\n typeStore.Duration = _a$1;\r\n})();\r\nDuration.NAME = \"Duration\";\n\nvar _a;\r\nclass TIME extends Utf8String {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 14;\r\n }\r\n}\r\n_a = TIME;\r\n(() => {\r\n typeStore.TIME = _a;\r\n})();\r\nTIME.NAME = \"TIME\";\n\nclass Any {\r\n constructor({ name = EMPTY_STRING, optional = false, } = {}) {\r\n this.name = name;\r\n this.optional = optional;\r\n }\r\n}\n\nclass Choice extends Any {\r\n constructor({ value = [], ...parameters } = {}) {\r\n super(parameters);\r\n this.value = value;\r\n }\r\n}\n\nclass Repeated extends Any {\r\n constructor({ value = new Any(), local = false, ...parameters } = {}) {\r\n super(parameters);\r\n this.value = value;\r\n this.local = local;\r\n }\r\n}\n\nclass RawData {\r\n constructor({ data = EMPTY_VIEW } = {}) {\r\n this.dataView = pvtsutils.BufferSourceConverter.toUint8Array(data);\r\n }\r\n get data() {\r\n return this.dataView.slice().buffer;\r\n }\r\n set data(value) {\r\n this.dataView = pvtsutils.BufferSourceConverter.toUint8Array(value);\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n const endLength = inputOffset + inputLength;\r\n this.dataView = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer).subarray(inputOffset, endLength);\r\n return endLength;\r\n }\r\n toBER(sizeOnly) {\r\n return this.dataView.slice().buffer;\r\n }\r\n}\n\nfunction compareSchema(root, inputData, inputSchema) {\r\n if (inputSchema instanceof Choice) {\r\n for (let j = 0; j < inputSchema.value.length; j++) {\r\n const result = compareSchema(root, inputData, inputSchema.value[j]);\r\n if (result.verified) {\r\n return {\r\n verified: true,\r\n result: root\r\n };\r\n }\r\n }\r\n {\r\n const _result = {\r\n verified: false,\r\n result: {\r\n error: \"Wrong values for Choice type\"\r\n },\r\n };\r\n if (inputSchema.hasOwnProperty(NAME))\r\n _result.name = inputSchema.name;\r\n return _result;\r\n }\r\n }\r\n if (inputSchema instanceof Any) {\r\n if (inputSchema.hasOwnProperty(NAME))\r\n root[inputSchema.name] = inputData;\r\n return {\r\n verified: true,\r\n result: root\r\n };\r\n }\r\n if ((root instanceof Object) === false) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong root object\" }\r\n };\r\n }\r\n if ((inputData instanceof Object) === false) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong ASN.1 data\" }\r\n };\r\n }\r\n if ((inputSchema instanceof Object) === false) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong ASN.1 schema\" }\r\n };\r\n }\r\n if ((ID_BLOCK in inputSchema) === false) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong ASN.1 schema\" }\r\n };\r\n }\r\n if ((FROM_BER in inputSchema.idBlock) === false) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong ASN.1 schema\" }\r\n };\r\n }\r\n if ((TO_BER in inputSchema.idBlock) === false) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong ASN.1 schema\" }\r\n };\r\n }\r\n const encodedId = inputSchema.idBlock.toBER(false);\r\n if (encodedId.byteLength === 0) {\r\n return {\r\n verified: false,\r\n result: { error: \"Error encoding idBlock for ASN.1 schema\" }\r\n };\r\n }\r\n const decodedOffset = inputSchema.idBlock.fromBER(encodedId, 0, encodedId.byteLength);\r\n if (decodedOffset === -1) {\r\n return {\r\n verified: false,\r\n result: { error: \"Error decoding idBlock for ASN.1 schema\" }\r\n };\r\n }\r\n if (inputSchema.idBlock.hasOwnProperty(TAG_CLASS) === false) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong ASN.1 schema\" }\r\n };\r\n }\r\n if (inputSchema.idBlock.tagClass !== inputData.idBlock.tagClass) {\r\n return {\r\n verified: false,\r\n result: root\r\n };\r\n }\r\n if (inputSchema.idBlock.hasOwnProperty(TAG_NUMBER) === false) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong ASN.1 schema\" }\r\n };\r\n }\r\n if (inputSchema.idBlock.tagNumber !== inputData.idBlock.tagNumber) {\r\n return {\r\n verified: false,\r\n result: root\r\n };\r\n }\r\n if (inputSchema.idBlock.hasOwnProperty(IS_CONSTRUCTED) === false) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong ASN.1 schema\" }\r\n };\r\n }\r\n if (inputSchema.idBlock.isConstructed !== inputData.idBlock.isConstructed) {\r\n return {\r\n verified: false,\r\n result: root\r\n };\r\n }\r\n if (!(IS_HEX_ONLY in inputSchema.idBlock)) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong ASN.1 schema\" }\r\n };\r\n }\r\n if (inputSchema.idBlock.isHexOnly !== inputData.idBlock.isHexOnly) {\r\n return {\r\n verified: false,\r\n result: root\r\n };\r\n }\r\n if (inputSchema.idBlock.isHexOnly) {\r\n if ((VALUE_HEX_VIEW in inputSchema.idBlock) === false) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong ASN.1 schema\" }\r\n };\r\n }\r\n const schemaView = inputSchema.idBlock.valueHexView;\r\n const asn1View = inputData.idBlock.valueHexView;\r\n if (schemaView.length !== asn1View.length) {\r\n return {\r\n verified: false,\r\n result: root\r\n };\r\n }\r\n for (let i = 0; i < schemaView.length; i++) {\r\n if (schemaView[i] !== asn1View[1]) {\r\n return {\r\n verified: false,\r\n result: root\r\n };\r\n }\r\n }\r\n }\r\n if (inputSchema.name) {\r\n inputSchema.name = inputSchema.name.replace(/^\\s+|\\s+$/g, EMPTY_STRING);\r\n if (inputSchema.name)\r\n root[inputSchema.name] = inputData;\r\n }\r\n if (inputSchema instanceof typeStore.Constructed) {\r\n let admission = 0;\r\n let result = {\r\n verified: false,\r\n result: {\r\n error: \"Unknown error\",\r\n }\r\n };\r\n let maxLength = inputSchema.valueBlock.value.length;\r\n if (maxLength > 0) {\r\n if (inputSchema.valueBlock.value[0] instanceof Repeated) {\r\n maxLength = inputData.valueBlock.value.length;\r\n }\r\n }\r\n if (maxLength === 0) {\r\n return {\r\n verified: true,\r\n result: root\r\n };\r\n }\r\n if ((inputData.valueBlock.value.length === 0) &&\r\n (inputSchema.valueBlock.value.length !== 0)) {\r\n let _optional = true;\r\n for (let i = 0; i < inputSchema.valueBlock.value.length; i++)\r\n _optional = _optional && (inputSchema.valueBlock.value[i].optional || false);\r\n if (_optional) {\r\n return {\r\n verified: true,\r\n result: root\r\n };\r\n }\r\n if (inputSchema.name) {\r\n inputSchema.name = inputSchema.name.replace(/^\\s+|\\s+$/g, EMPTY_STRING);\r\n if (inputSchema.name)\r\n delete root[inputSchema.name];\r\n }\r\n root.error = \"Inconsistent object length\";\r\n return {\r\n verified: false,\r\n result: root\r\n };\r\n }\r\n for (let i = 0; i < maxLength; i++) {\r\n if ((i - admission) >= inputData.valueBlock.value.length) {\r\n if (inputSchema.valueBlock.value[i].optional === false) {\r\n const _result = {\r\n verified: false,\r\n result: root\r\n };\r\n root.error = \"Inconsistent length between ASN.1 data and schema\";\r\n if (inputSchema.name) {\r\n inputSchema.name = inputSchema.name.replace(/^\\s+|\\s+$/g, EMPTY_STRING);\r\n if (inputSchema.name) {\r\n delete root[inputSchema.name];\r\n _result.name = inputSchema.name;\r\n }\r\n }\r\n return _result;\r\n }\r\n }\r\n else {\r\n if (inputSchema.valueBlock.value[0] instanceof Repeated) {\r\n result = compareSchema(root, inputData.valueBlock.value[i], inputSchema.valueBlock.value[0].value);\r\n if (result.verified === false) {\r\n if (inputSchema.valueBlock.value[0].optional)\r\n admission++;\r\n else {\r\n if (inputSchema.name) {\r\n inputSchema.name = inputSchema.name.replace(/^\\s+|\\s+$/g, EMPTY_STRING);\r\n if (inputSchema.name)\r\n delete root[inputSchema.name];\r\n }\r\n return result;\r\n }\r\n }\r\n if ((NAME in inputSchema.valueBlock.value[0]) && (inputSchema.valueBlock.value[0].name.length > 0)) {\r\n let arrayRoot = {};\r\n if ((LOCAL in inputSchema.valueBlock.value[0]) && (inputSchema.valueBlock.value[0].local))\r\n arrayRoot = inputData;\r\n else\r\n arrayRoot = root;\r\n if (typeof arrayRoot[inputSchema.valueBlock.value[0].name] === \"undefined\")\r\n arrayRoot[inputSchema.valueBlock.value[0].name] = [];\r\n arrayRoot[inputSchema.valueBlock.value[0].name].push(inputData.valueBlock.value[i]);\r\n }\r\n }\r\n else {\r\n result = compareSchema(root, inputData.valueBlock.value[i - admission], inputSchema.valueBlock.value[i]);\r\n if (result.verified === false) {\r\n if (inputSchema.valueBlock.value[i].optional)\r\n admission++;\r\n else {\r\n if (inputSchema.name) {\r\n inputSchema.name = inputSchema.name.replace(/^\\s+|\\s+$/g, EMPTY_STRING);\r\n if (inputSchema.name)\r\n delete root[inputSchema.name];\r\n }\r\n return result;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n if (result.verified === false) {\r\n const _result = {\r\n verified: false,\r\n result: root\r\n };\r\n if (inputSchema.name) {\r\n inputSchema.name = inputSchema.name.replace(/^\\s+|\\s+$/g, EMPTY_STRING);\r\n if (inputSchema.name) {\r\n delete root[inputSchema.name];\r\n _result.name = inputSchema.name;\r\n }\r\n }\r\n return _result;\r\n }\r\n return {\r\n verified: true,\r\n result: root\r\n };\r\n }\r\n if (inputSchema.primitiveSchema &&\r\n (VALUE_HEX_VIEW in inputData.valueBlock)) {\r\n const asn1 = localFromBER(inputData.valueBlock.valueHexView);\r\n if (asn1.offset === -1) {\r\n const _result = {\r\n verified: false,\r\n result: asn1.result\r\n };\r\n if (inputSchema.name) {\r\n inputSchema.name = inputSchema.name.replace(/^\\s+|\\s+$/g, EMPTY_STRING);\r\n if (inputSchema.name) {\r\n delete root[inputSchema.name];\r\n _result.name = inputSchema.name;\r\n }\r\n }\r\n return _result;\r\n }\r\n return compareSchema(root, asn1.result, inputSchema.primitiveSchema);\r\n }\r\n return {\r\n verified: true,\r\n result: root\r\n };\r\n}\r\nfunction verifySchema(inputBuffer, inputSchema) {\r\n if ((inputSchema instanceof Object) === false) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong ASN.1 schema type\" }\r\n };\r\n }\r\n const asn1 = localFromBER(pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer));\r\n if (asn1.offset === -1) {\r\n return {\r\n verified: false,\r\n result: asn1.result\r\n };\r\n }\r\n return compareSchema(asn1.result, asn1.result, inputSchema);\r\n}\n\nexport { Any, BaseBlock, BaseStringBlock, BitString, BmpString, Boolean, CharacterString, Choice, Constructed, DATE, DateTime, Duration, EndOfContent, Enumerated, GeneralString, GeneralizedTime, GraphicString, HexBlock, IA5String, Integer, Null, NumericString, ObjectIdentifier, OctetString, Primitive, PrintableString, RawData, RelativeObjectIdentifier, Repeated, Sequence, Set, TIME, TeletexString, TimeOfDay, UTCTime, UniversalString, Utf8String, ValueBlock, VideotexString, ViewWriter, VisibleString, compareSchema, fromBER, verifySchema };\n", "/*!\n Copyright (c) Peculiar Ventures, LLC\n*/\n\nfunction getUTCDate(date) {\r\n return new Date(date.getTime() + (date.getTimezoneOffset() * 60000));\r\n}\r\nfunction getParametersValue(parameters, name, defaultValue) {\r\n var _a;\r\n if ((parameters instanceof Object) === false) {\r\n return defaultValue;\r\n }\r\n return (_a = parameters[name]) !== null && _a !== void 0 ? _a : defaultValue;\r\n}\r\nfunction bufferToHexCodes(inputBuffer, inputOffset = 0, inputLength = (inputBuffer.byteLength - inputOffset), insertSpace = false) {\r\n let result = \"\";\r\n for (const item of (new Uint8Array(inputBuffer, inputOffset, inputLength))) {\r\n const str = item.toString(16).toUpperCase();\r\n if (str.length === 1) {\r\n result += \"0\";\r\n }\r\n result += str;\r\n if (insertSpace) {\r\n result += \" \";\r\n }\r\n }\r\n return result.trim();\r\n}\r\nfunction checkBufferParams(baseBlock, inputBuffer, inputOffset, inputLength) {\r\n if (!(inputBuffer instanceof ArrayBuffer)) {\r\n baseBlock.error = \"Wrong parameter: inputBuffer must be \\\"ArrayBuffer\\\"\";\r\n return false;\r\n }\r\n if (!inputBuffer.byteLength) {\r\n baseBlock.error = \"Wrong parameter: inputBuffer has zero length\";\r\n return false;\r\n }\r\n if (inputOffset < 0) {\r\n baseBlock.error = \"Wrong parameter: inputOffset less than zero\";\r\n return false;\r\n }\r\n if (inputLength < 0) {\r\n baseBlock.error = \"Wrong parameter: inputLength less than zero\";\r\n return false;\r\n }\r\n if ((inputBuffer.byteLength - inputOffset - inputLength) < 0) {\r\n baseBlock.error = \"End of input reached before message was fully decoded (inconsistent offset and length values)\";\r\n return false;\r\n }\r\n return true;\r\n}\r\nfunction utilFromBase(inputBuffer, inputBase) {\r\n let result = 0;\r\n if (inputBuffer.length === 1) {\r\n return inputBuffer[0];\r\n }\r\n for (let i = (inputBuffer.length - 1); i >= 0; i--) {\r\n result += inputBuffer[(inputBuffer.length - 1) - i] * Math.pow(2, inputBase * i);\r\n }\r\n return result;\r\n}\r\nfunction utilToBase(value, base, reserved = (-1)) {\r\n const internalReserved = reserved;\r\n let internalValue = value;\r\n let result = 0;\r\n let biggest = Math.pow(2, base);\r\n for (let i = 1; i < 8; i++) {\r\n if (value < biggest) {\r\n let retBuf;\r\n if (internalReserved < 0) {\r\n retBuf = new ArrayBuffer(i);\r\n result = i;\r\n }\r\n else {\r\n if (internalReserved < i) {\r\n return (new ArrayBuffer(0));\r\n }\r\n retBuf = new ArrayBuffer(internalReserved);\r\n result = internalReserved;\r\n }\r\n const retView = new Uint8Array(retBuf);\r\n for (let j = (i - 1); j >= 0; j--) {\r\n const basis = Math.pow(2, j * base);\r\n retView[result - j - 1] = Math.floor(internalValue / basis);\r\n internalValue -= (retView[result - j - 1]) * basis;\r\n }\r\n return retBuf;\r\n }\r\n biggest *= Math.pow(2, base);\r\n }\r\n return new ArrayBuffer(0);\r\n}\r\nfunction utilConcatBuf(...buffers) {\r\n let outputLength = 0;\r\n let prevLength = 0;\r\n for (const buffer of buffers) {\r\n outputLength += buffer.byteLength;\r\n }\r\n const retBuf = new ArrayBuffer(outputLength);\r\n const retView = new Uint8Array(retBuf);\r\n for (const buffer of buffers) {\r\n retView.set(new Uint8Array(buffer), prevLength);\r\n prevLength += buffer.byteLength;\r\n }\r\n return retBuf;\r\n}\r\nfunction utilConcatView(...views) {\r\n let outputLength = 0;\r\n let prevLength = 0;\r\n for (const view of views) {\r\n outputLength += view.length;\r\n }\r\n const retBuf = new ArrayBuffer(outputLength);\r\n const retView = new Uint8Array(retBuf);\r\n for (const view of views) {\r\n retView.set(view, prevLength);\r\n prevLength += view.length;\r\n }\r\n return retView;\r\n}\r\nfunction utilDecodeTC() {\r\n const buf = new Uint8Array(this.valueHex);\r\n if (this.valueHex.byteLength >= 2) {\r\n const condition1 = (buf[0] === 0xFF) && (buf[1] & 0x80);\r\n const condition2 = (buf[0] === 0x00) && ((buf[1] & 0x80) === 0x00);\r\n if (condition1 || condition2) {\r\n this.warnings.push(\"Needlessly long format\");\r\n }\r\n }\r\n const bigIntBuffer = new ArrayBuffer(this.valueHex.byteLength);\r\n const bigIntView = new Uint8Array(bigIntBuffer);\r\n for (let i = 0; i < this.valueHex.byteLength; i++) {\r\n bigIntView[i] = 0;\r\n }\r\n bigIntView[0] = (buf[0] & 0x80);\r\n const bigInt = utilFromBase(bigIntView, 8);\r\n const smallIntBuffer = new ArrayBuffer(this.valueHex.byteLength);\r\n const smallIntView = new Uint8Array(smallIntBuffer);\r\n for (let j = 0; j < this.valueHex.byteLength; j++) {\r\n smallIntView[j] = buf[j];\r\n }\r\n smallIntView[0] &= 0x7F;\r\n const smallInt = utilFromBase(smallIntView, 8);\r\n return (smallInt - bigInt);\r\n}\r\nfunction utilEncodeTC(value) {\r\n const modValue = (value < 0) ? (value * (-1)) : value;\r\n let bigInt = 128;\r\n for (let i = 1; i < 8; i++) {\r\n if (modValue <= bigInt) {\r\n if (value < 0) {\r\n const smallInt = bigInt - modValue;\r\n const retBuf = utilToBase(smallInt, 8, i);\r\n const retView = new Uint8Array(retBuf);\r\n retView[0] |= 0x80;\r\n return retBuf;\r\n }\r\n let retBuf = utilToBase(modValue, 8, i);\r\n let retView = new Uint8Array(retBuf);\r\n if (retView[0] & 0x80) {\r\n const tempBuf = retBuf.slice(0);\r\n const tempView = new Uint8Array(tempBuf);\r\n retBuf = new ArrayBuffer(retBuf.byteLength + 1);\r\n retView = new Uint8Array(retBuf);\r\n for (let k = 0; k < tempBuf.byteLength; k++) {\r\n retView[k + 1] = tempView[k];\r\n }\r\n retView[0] = 0x00;\r\n }\r\n return retBuf;\r\n }\r\n bigInt *= Math.pow(2, 8);\r\n }\r\n return (new ArrayBuffer(0));\r\n}\r\nfunction isEqualBuffer(inputBuffer1, inputBuffer2) {\r\n if (inputBuffer1.byteLength !== inputBuffer2.byteLength) {\r\n return false;\r\n }\r\n const view1 = new Uint8Array(inputBuffer1);\r\n const view2 = new Uint8Array(inputBuffer2);\r\n for (let i = 0; i < view1.length; i++) {\r\n if (view1[i] !== view2[i]) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n}\r\nfunction padNumber(inputNumber, fullLength) {\r\n const str = inputNumber.toString(10);\r\n if (fullLength < str.length) {\r\n return \"\";\r\n }\r\n const dif = fullLength - str.length;\r\n const padding = new Array(dif);\r\n for (let i = 0; i < dif; i++) {\r\n padding[i] = \"0\";\r\n }\r\n const paddingString = padding.join(\"\");\r\n return paddingString.concat(str);\r\n}\r\nconst base64Template = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\";\r\nconst base64UrlTemplate = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=\";\r\nfunction toBase64(input, useUrlTemplate = false, skipPadding = false, skipLeadingZeros = false) {\r\n let i = 0;\r\n let flag1 = 0;\r\n let flag2 = 0;\r\n let output = \"\";\r\n const template = (useUrlTemplate) ? base64UrlTemplate : base64Template;\r\n if (skipLeadingZeros) {\r\n let nonZeroPosition = 0;\r\n for (let i = 0; i < input.length; i++) {\r\n if (input.charCodeAt(i) !== 0) {\r\n nonZeroPosition = i;\r\n break;\r\n }\r\n }\r\n input = input.slice(nonZeroPosition);\r\n }\r\n while (i < input.length) {\r\n const chr1 = input.charCodeAt(i++);\r\n if (i >= input.length) {\r\n flag1 = 1;\r\n }\r\n const chr2 = input.charCodeAt(i++);\r\n if (i >= input.length) {\r\n flag2 = 1;\r\n }\r\n const chr3 = input.charCodeAt(i++);\r\n const enc1 = chr1 >> 2;\r\n const enc2 = ((chr1 & 0x03) << 4) | (chr2 >> 4);\r\n let enc3 = ((chr2 & 0x0F) << 2) | (chr3 >> 6);\r\n let enc4 = chr3 & 0x3F;\r\n if (flag1 === 1) {\r\n enc3 = enc4 = 64;\r\n }\r\n else {\r\n if (flag2 === 1) {\r\n enc4 = 64;\r\n }\r\n }\r\n if (skipPadding) {\r\n if (enc3 === 64) {\r\n output += `${template.charAt(enc1)}${template.charAt(enc2)}`;\r\n }\r\n else {\r\n if (enc4 === 64) {\r\n output += `${template.charAt(enc1)}${template.charAt(enc2)}${template.charAt(enc3)}`;\r\n }\r\n else {\r\n output += `${template.charAt(enc1)}${template.charAt(enc2)}${template.charAt(enc3)}${template.charAt(enc4)}`;\r\n }\r\n }\r\n }\r\n else {\r\n output += `${template.charAt(enc1)}${template.charAt(enc2)}${template.charAt(enc3)}${template.charAt(enc4)}`;\r\n }\r\n }\r\n return output;\r\n}\r\nfunction fromBase64(input, useUrlTemplate = false, cutTailZeros = false) {\r\n const template = (useUrlTemplate) ? base64UrlTemplate : base64Template;\r\n function indexOf(toSearch) {\r\n for (let i = 0; i < 64; i++) {\r\n if (template.charAt(i) === toSearch)\r\n return i;\r\n }\r\n return 64;\r\n }\r\n function test(incoming) {\r\n return ((incoming === 64) ? 0x00 : incoming);\r\n }\r\n let i = 0;\r\n let output = \"\";\r\n while (i < input.length) {\r\n const enc1 = indexOf(input.charAt(i++));\r\n const enc2 = (i >= input.length) ? 0x00 : indexOf(input.charAt(i++));\r\n const enc3 = (i >= input.length) ? 0x00 : indexOf(input.charAt(i++));\r\n const enc4 = (i >= input.length) ? 0x00 : indexOf(input.charAt(i++));\r\n const chr1 = (test(enc1) << 2) | (test(enc2) >> 4);\r\n const chr2 = ((test(enc2) & 0x0F) << 4) | (test(enc3) >> 2);\r\n const chr3 = ((test(enc3) & 0x03) << 6) | test(enc4);\r\n output += String.fromCharCode(chr1);\r\n if (enc3 !== 64) {\r\n output += String.fromCharCode(chr2);\r\n }\r\n if (enc4 !== 64) {\r\n output += String.fromCharCode(chr3);\r\n }\r\n }\r\n if (cutTailZeros) {\r\n const outputLength = output.length;\r\n let nonZeroStart = (-1);\r\n for (let i = (outputLength - 1); i >= 0; i--) {\r\n if (output.charCodeAt(i) !== 0) {\r\n nonZeroStart = i;\r\n break;\r\n }\r\n }\r\n if (nonZeroStart !== (-1)) {\r\n output = output.slice(0, nonZeroStart + 1);\r\n }\r\n else {\r\n output = \"\";\r\n }\r\n }\r\n return output;\r\n}\r\nfunction arrayBufferToString(buffer) {\r\n let resultString = \"\";\r\n const view = new Uint8Array(buffer);\r\n for (const element of view) {\r\n resultString += String.fromCharCode(element);\r\n }\r\n return resultString;\r\n}\r\nfunction stringToArrayBuffer(str) {\r\n const stringLength = str.length;\r\n const resultBuffer = new ArrayBuffer(stringLength);\r\n const resultView = new Uint8Array(resultBuffer);\r\n for (let i = 0; i < stringLength; i++) {\r\n resultView[i] = str.charCodeAt(i);\r\n }\r\n return resultBuffer;\r\n}\r\nconst log2 = Math.log(2);\r\nfunction nearestPowerOf2(length) {\r\n const base = (Math.log(length) / log2);\r\n const floor = Math.floor(base);\r\n const round = Math.round(base);\r\n return ((floor === round) ? floor : round);\r\n}\r\nfunction clearProps(object, propsArray) {\r\n for (const prop of propsArray) {\r\n delete object[prop];\r\n }\r\n}\n\nexport { arrayBufferToString, bufferToHexCodes, checkBufferParams, clearProps, fromBase64, getParametersValue, getUTCDate, isEqualBuffer, nearestPowerOf2, padNumber, stringToArrayBuffer, toBase64, utilConcatBuf, utilConcatView, utilDecodeTC, utilEncodeTC, utilFromBase, utilToBase };\n", null, null, null, "/** @fileOverview Javascript cryptography implementation.\n *\n * Crush to remove comments, shorten variable names and\n * generally reduce transmission size.\n *\n * @author Emily Stark\n * @author Mike Hamburg\n * @author Dan Boneh\n */\n\"use strict\";\n/*jslint indent: 2, bitwise: false, nomen: false, plusplus: false, white: false, regexp: false */\n/*global document, window, escape, unescape, module, require, Uint32Array */\n/**\n * The Stanford Javascript Crypto Library, top-level namespace.\n * @namespace\n */\nvar sjcl = {\n /**\n * Symmetric ciphers.\n * @namespace\n */\n cipher: {},\n /**\n * Hash functions. Right now only SHA256 is implemented.\n * @namespace\n */\n hash: {},\n /**\n * Key exchange functions. Right now only SRP is implemented.\n * @namespace\n */\n keyexchange: {},\n /**\n * Cipher modes of operation.\n * @namespace\n */\n mode: {},\n /**\n * Miscellaneous. HMAC and PBKDF2.\n * @namespace\n */\n misc: {},\n /**\n * Bit array encoders and decoders.\n * @namespace\n *\n * @description\n * The members of this namespace are functions which translate between\n * SJCL's bitArrays and other objects (usually strings). Because it\n * isn't always clear which direction is encoding and which is decoding,\n * the method names are \"fromBits\" and \"toBits\".\n */\n codec: {},\n /**\n * Exceptions.\n * @namespace\n */\n exception: {\n /**\n * Ciphertext is corrupt.\n * @constructor\n */\n corrupt: function (message) {\n this.toString = function () { return \"CORRUPT: \" + this.message; };\n this.message = message;\n },\n /**\n * Invalid parameter.\n * @constructor\n */\n invalid: function (message) {\n this.toString = function () { return \"INVALID: \" + this.message; };\n this.message = message;\n },\n /**\n * Bug or missing feature in SJCL.\n * @constructor\n */\n bug: function (message) {\n this.toString = function () { return \"BUG: \" + this.message; };\n this.message = message;\n },\n /**\n * Something isn't ready.\n * @constructor\n */\n notReady: function (message) {\n this.toString = function () { return \"NOT READY: \" + this.message; };\n this.message = message;\n }\n }\n};\n/** @fileOverview Low-level AES implementation.\n *\n * This file contains a low-level implementation of AES, optimized for\n * size and for efficiency on several browsers. It is based on\n * OpenSSL's aes_core.c, a public-domain implementation by Vincent\n * Rijmen, Antoon Bosselaers and Paulo Barreto.\n *\n * An older version of this implementation is available in the public\n * domain, but this one is (c) Emily Stark, Mike Hamburg, Dan Boneh,\n * Stanford University 2008-2010 and BSD-licensed for liability\n * reasons.\n *\n * @author Emily Stark\n * @author Mike Hamburg\n * @author Dan Boneh\n */\n/**\n * Schedule out an AES key for both encryption and decryption. This\n * is a low-level class. Use a cipher mode to do bulk encryption.\n *\n * @constructor\n * @param {Array} key The key as an array of 4, 6 or 8 words.\n */\nsjcl.cipher.aes = function (key) {\n if (!this._tables[0][0][0]) {\n this._precompute();\n }\n var i, j, tmp, encKey, decKey, sbox = this._tables[0][4], decTable = this._tables[1], keyLen = key.length, rcon = 1;\n if (keyLen !== 4 && keyLen !== 6 && keyLen !== 8) {\n throw new sjcl.exception.invalid(\"invalid aes key size\");\n }\n this._key = [encKey = key.slice(0), decKey = []];\n // schedule encryption keys\n for (i = keyLen; i < 4 * keyLen + 28; i++) {\n tmp = encKey[i - 1];\n // apply sbox\n if (i % keyLen === 0 || (keyLen === 8 && i % keyLen === 4)) {\n tmp = sbox[tmp >>> 24] << 24 ^ sbox[tmp >> 16 & 255] << 16 ^ sbox[tmp >> 8 & 255] << 8 ^ sbox[tmp & 255];\n // shift rows and add rcon\n if (i % keyLen === 0) {\n tmp = tmp << 8 ^ tmp >>> 24 ^ rcon << 24;\n rcon = rcon << 1 ^ (rcon >> 7) * 283;\n }\n }\n encKey[i] = encKey[i - keyLen] ^ tmp;\n }\n // schedule decryption keys\n for (j = 0; i; j++, i--) {\n tmp = encKey[j & 3 ? i : i - 4];\n if (i <= 4 || j < 4) {\n decKey[j] = tmp;\n }\n else {\n decKey[j] = decTable[0][sbox[tmp >>> 24]] ^\n decTable[1][sbox[tmp >> 16 & 255]] ^\n decTable[2][sbox[tmp >> 8 & 255]] ^\n decTable[3][sbox[tmp & 255]];\n }\n }\n};\nsjcl.cipher.aes.prototype = {\n // public\n /* Something like this might appear here eventually\n name: \"AES\",\n blockSize: 4,\n keySizes: [4,6,8],\n */\n /**\n * Encrypt an array of 4 big-endian words.\n * @param {Array} data The plaintext.\n * @return {Array} The ciphertext.\n */\n encrypt: function (data) { return this._crypt(data, 0); },\n /**\n * Decrypt an array of 4 big-endian words.\n * @param {Array} data The ciphertext.\n * @return {Array} The plaintext.\n */\n decrypt: function (data) { return this._crypt(data, 1); },\n /**\n * The expanded S-box and inverse S-box tables. These will be computed\n * on the client so that we don't have to send them down the wire.\n *\n * There are two tables, _tables[0] is for encryption and\n * _tables[1] is for decryption.\n *\n * The first 4 sub-tables are the expanded S-box with MixColumns. The\n * last (_tables[01][4]) is the S-box itself.\n *\n * @private\n */\n _tables: [[[], [], [], [], []], [[], [], [], [], []]],\n /**\n * Expand the S-box tables.\n *\n * @private\n */\n _precompute: function () {\n var encTable = this._tables[0], decTable = this._tables[1], sbox = encTable[4], sboxInv = decTable[4], i, x, xInv, d = [], th = [], x2, x4, x8, s, tEnc, tDec;\n // Compute double and third tables\n for (i = 0; i < 256; i++) {\n th[(d[i] = i << 1 ^ (i >> 7) * 283) ^ i] = i;\n }\n for (x = xInv = 0; !sbox[x]; x ^= x2 || 1, xInv = th[xInv] || 1) {\n // Compute sbox\n s = xInv ^ xInv << 1 ^ xInv << 2 ^ xInv << 3 ^ xInv << 4;\n s = s >> 8 ^ s & 255 ^ 99;\n sbox[x] = s;\n sboxInv[s] = x;\n // Compute MixColumns\n x8 = d[x4 = d[x2 = d[x]]];\n tDec = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;\n tEnc = d[s] * 0x101 ^ s * 0x1010100;\n for (i = 0; i < 4; i++) {\n encTable[i][x] = tEnc = tEnc << 24 ^ tEnc >>> 8;\n decTable[i][s] = tDec = tDec << 24 ^ tDec >>> 8;\n }\n }\n // Compactify. Considerable speedup on Firefox.\n for (i = 0; i < 5; i++) {\n encTable[i] = encTable[i].slice(0);\n decTable[i] = decTable[i].slice(0);\n }\n },\n /**\n * Encryption and decryption core.\n * @param {Array} input Four words to be encrypted or decrypted.\n * @param dir The direction, 0 for encrypt and 1 for decrypt.\n * @return {Array} The four encrypted or decrypted words.\n * @private\n */\n _crypt: function (input, dir) {\n if (input.length !== 4) {\n throw new sjcl.exception.invalid(\"invalid aes block size\");\n }\n var key = this._key[dir], \n // state variables a,b,c,d are loaded with pre-whitened data\n a = input[0] ^ key[0], b = input[dir ? 3 : 1] ^ key[1], c = input[2] ^ key[2], d = input[dir ? 1 : 3] ^ key[3], a2, b2, c2, nInnerRounds = key.length / 4 - 2, i, kIndex = 4, out = [0, 0, 0, 0], table = this._tables[dir], \n // load up the tables\n t0 = table[0], t1 = table[1], t2 = table[2], t3 = table[3], sbox = table[4];\n // Inner rounds. Cribbed from OpenSSL.\n for (i = 0; i < nInnerRounds; i++) {\n a2 = t0[a >>> 24] ^ t1[b >> 16 & 255] ^ t2[c >> 8 & 255] ^ t3[d & 255] ^ key[kIndex];\n b2 = t0[b >>> 24] ^ t1[c >> 16 & 255] ^ t2[d >> 8 & 255] ^ t3[a & 255] ^ key[kIndex + 1];\n c2 = t0[c >>> 24] ^ t1[d >> 16 & 255] ^ t2[a >> 8 & 255] ^ t3[b & 255] ^ key[kIndex + 2];\n d = t0[d >>> 24] ^ t1[a >> 16 & 255] ^ t2[b >> 8 & 255] ^ t3[c & 255] ^ key[kIndex + 3];\n kIndex += 4;\n a = a2;\n b = b2;\n c = c2;\n }\n // Last round.\n for (i = 0; i < 4; i++) {\n out[dir ? 3 & -i : i] =\n sbox[a >>> 24] << 24 ^\n sbox[b >> 16 & 255] << 16 ^\n sbox[c >> 8 & 255] << 8 ^\n sbox[d & 255] ^\n key[kIndex++];\n a2 = a;\n a = b;\n b = c;\n c = d;\n d = a2;\n }\n return out;\n }\n};\n/** @fileOverview Arrays of bits, encoded as arrays of Numbers.\n *\n * @author Emily Stark\n * @author Mike Hamburg\n * @author Dan Boneh\n */\n/**\n * Arrays of bits, encoded as arrays of Numbers.\n * @namespace\n * @description\n *\n * These objects are the currency accepted by SJCL's crypto functions.\n *
\n *\n *\n * Most of our crypto primitives operate on arrays of 4-byte words internally,\n * but many of them can take arguments that are not a multiple of 4 bytes.\n * This library encodes arrays of bits (whose size need not be a multiple of 8\n * bits) as arrays of 32-bit words. The bits are packed, big-endian, into an\n * array of words, 32 bits at a time. Since the words are double-precision\n * floating point numbers, they fit some extra data. We use this (in a private,\n * possibly-changing manner) to encode the number of bits actually present\n * in the last word of the array.\n *
\n *\n *\n * Because bitwise ops clear this out-of-band data, these arrays can be passed\n * to ciphers like AES which want arrays of words.\n *
\n */\nsjcl.bitArray = {\n /**\n * Array slices in units of bits.\n * @param {bitArray} a The array to slice.\n * @param {Number} bstart The offset to the start of the slice, in bits.\n * @param {Number} bend The offset to the end of the slice, in bits. If this is undefined,\n * slice until the end of the array.\n * @return {bitArray} The requested slice.\n */\n bitSlice: function (a, bstart, bend) {\n a = sjcl.bitArray._shiftRight(a.slice(bstart / 32), 32 - (bstart & 31)).slice(1);\n return (bend === undefined) ? a : sjcl.bitArray.clamp(a, bend - bstart);\n },\n /**\n * Extract a number packed into a bit array.\n * @param {bitArray} a The array to slice.\n * @param {Number} bstart The offset to the start of the slice, in bits.\n * @param {Number} blength The length of the number to extract.\n * @return {Number} The requested slice.\n */\n extract: function (a, bstart, blength) {\n // FIXME: this Math.floor is not necessary at all, but for some reason\n // seems to suppress a bug in the Chromium JIT.\n var x, sh = Math.floor((-bstart - blength) & 31);\n if ((bstart + blength - 1 ^ bstart) & -32) {\n // it crosses a boundary\n x = (a[bstart / 32 | 0] << (32 - sh)) ^ (a[bstart / 32 + 1 | 0] >>> sh);\n }\n else {\n // within a single word\n x = a[bstart / 32 | 0] >>> sh;\n }\n return x & ((1 << blength) - 1);\n },\n /**\n * Concatenate two bit arrays.\n * @param {bitArray} a1 The first array.\n * @param {bitArray} a2 The second array.\n * @return {bitArray} The concatenation of a1 and a2.\n */\n concat: function (a1, a2) {\n if (a1.length === 0 || a2.length === 0) {\n return a1.concat(a2);\n }\n var last = a1[a1.length - 1], shift = sjcl.bitArray.getPartial(last);\n if (shift === 32) {\n return a1.concat(a2);\n }\n else {\n return sjcl.bitArray._shiftRight(a2, shift, last | 0, a1.slice(0, a1.length - 1));\n }\n },\n /**\n * Find the length of an array of bits.\n * @param {bitArray} a The array.\n * @return {Number} The length of a, in bits.\n */\n bitLength: function (a) {\n var l = a.length, x;\n if (l === 0) {\n return 0;\n }\n x = a[l - 1];\n return (l - 1) * 32 + sjcl.bitArray.getPartial(x);\n },\n /**\n * Truncate an array.\n * @param {bitArray} a The array.\n * @param {Number} len The length to truncate to, in bits.\n * @return {bitArray} A new array, truncated to len bits.\n */\n clamp: function (a, len) {\n if (a.length * 32 < len) {\n return a;\n }\n a = a.slice(0, Math.ceil(len / 32));\n var l = a.length;\n len = len & 31;\n if (l > 0 && len) {\n a[l - 1] = sjcl.bitArray.partial(len, a[l - 1] & 0x80000000 >> (len - 1), 1);\n }\n return a;\n },\n /**\n * Make a partial word for a bit array.\n * @param {Number} len The number of bits in the word.\n * @param {Number} x The bits.\n * @param {Number} [_end=0] Pass 1 if x has already been shifted to the high side.\n * @return {Number} The partial word.\n */\n partial: function (len, x, _end) {\n if (len === 32) {\n return x;\n }\n return (_end ? x | 0 : x << (32 - len)) + len * 0x10000000000;\n },\n /**\n * Get the number of bits used by a partial word.\n * @param {Number} x The partial word.\n * @return {Number} The number of bits used by the partial word.\n */\n getPartial: function (x) {\n return Math.round(x / 0x10000000000) || 32;\n },\n /**\n * Compare two arrays for equality in a predictable amount of time.\n * @param {bitArray} a The first array.\n * @param {bitArray} b The second array.\n * @return {boolean} true if a == b; false otherwise.\n */\n equal: function (a, b) {\n if (sjcl.bitArray.bitLength(a) !== sjcl.bitArray.bitLength(b)) {\n return false;\n }\n var x = 0, i;\n for (i = 0; i < a.length; i++) {\n x |= a[i] ^ b[i];\n }\n return (x === 0);\n },\n /** Shift an array right.\n * @param {bitArray} a The array to shift.\n * @param {Number} shift The number of bits to shift.\n * @param {Number} [carry=0] A byte to carry in\n * @param {bitArray} [out=[]] An array to prepend to the output.\n * @private\n */\n _shiftRight: function (a, shift, carry, out) {\n var i, last2 = 0, shift2;\n if (out === undefined) {\n out = [];\n }\n for (; shift >= 32; shift -= 32) {\n out.push(carry);\n carry = 0;\n }\n if (shift === 0) {\n return out.concat(a);\n }\n for (i = 0; i < a.length; i++) {\n out.push(carry | a[i] >>> shift);\n carry = a[i] << (32 - shift);\n }\n last2 = a.length ? a[a.length - 1] : 0;\n shift2 = sjcl.bitArray.getPartial(last2);\n out.push(sjcl.bitArray.partial(shift + shift2 & 31, (shift + shift2 > 32) ? carry : out.pop(), 1));\n return out;\n },\n /** xor a block of 4 words together.\n * @private\n */\n _xor4: function (x, y) {\n return [x[0] ^ y[0], x[1] ^ y[1], x[2] ^ y[2], x[3] ^ y[3]];\n },\n /** byteswap a word array inplace.\n * (does not handle partial words)\n * @param {sjcl.bitArray} a word array\n * @return {sjcl.bitArray} byteswapped array\n */\n byteswapM: function (a) {\n var i, v, m = 0xff00;\n for (i = 0; i < a.length; ++i) {\n v = a[i];\n a[i] = (v >>> 24) | ((v >>> 8) & m) | ((v & m) << 8) | (v << 24);\n }\n return a;\n }\n};\n/** @fileOverview Bit array codec implementations.\n *\n * @author Emily Stark\n * @author Mike Hamburg\n * @author Dan Boneh\n */\n/**\n * UTF-8 strings\n * @namespace\n */\nsjcl.codec.utf8String = {\n /** Convert from a bitArray to a UTF-8 string. */\n fromBits: function (arr) {\n var out = \"\", bl = sjcl.bitArray.bitLength(arr), i, tmp;\n for (i = 0; i < bl / 8; i++) {\n if ((i & 3) === 0) {\n tmp = arr[i / 4];\n }\n out += String.fromCharCode(tmp >>> 8 >>> 8 >>> 8);\n tmp <<= 8;\n }\n return decodeURIComponent(escape(out));\n },\n /** Convert from a UTF-8 string to a bitArray. */\n toBits: function (str) {\n str = unescape(encodeURIComponent(str));\n var out = [], i, tmp = 0;\n for (i = 0; i < str.length; i++) {\n tmp = tmp << 8 | str.charCodeAt(i);\n if ((i & 3) === 3) {\n out.push(tmp);\n tmp = 0;\n }\n }\n if (i & 3) {\n out.push(sjcl.bitArray.partial(8 * (i & 3), tmp));\n }\n return out;\n }\n};\n/** @fileOverview Bit array codec implementations.\n *\n * @author Emily Stark\n * @author Mike Hamburg\n * @author Dan Boneh\n */\n/**\n * Hexadecimal\n * @namespace\n */\nsjcl.codec.hex = {\n /** Convert from a bitArray to a hex string. */\n fromBits: function (arr) {\n var out = \"\", i;\n for (i = 0; i < arr.length; i++) {\n out += ((arr[i] | 0) + 0xF00000000000).toString(16).substr(4);\n }\n return out.substr(0, sjcl.bitArray.bitLength(arr) / 4); //.replace(/(.{8})/g, \"$1 \");\n },\n /** Convert from a hex string to a bitArray. */\n toBits: function (str) {\n var i, out = [], len;\n str = str.replace(/\\s|0x/g, \"\");\n len = str.length;\n str = str + \"00000000\";\n for (i = 0; i < str.length; i += 8) {\n out.push(parseInt(str.substr(i, 8), 16) ^ 0);\n }\n return sjcl.bitArray.clamp(out, len * 4);\n }\n};\n/** @fileOverview Bit array codec implementations.\n *\n * @author Emily Stark\n * @author Mike Hamburg\n * @author Dan Boneh\n */\n/**\n * Base64 encoding/decoding\n * @namespace\n */\nsjcl.codec.base64 = {\n /** The base64 alphabet.\n * @private\n */\n _chars: \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\",\n /** Convert from a bitArray to a base64 string. */\n fromBits: function (arr, _noEquals, _url) {\n var out = \"\", i, bits = 0, c = sjcl.codec.base64._chars, ta = 0, bl = sjcl.bitArray.bitLength(arr);\n if (_url) {\n c = c.substr(0, 62) + '-_';\n }\n for (i = 0; out.length * 6 < bl;) {\n out += c.charAt((ta ^ arr[i] >>> bits) >>> 26);\n if (bits < 6) {\n ta = arr[i] << (6 - bits);\n bits += 26;\n i++;\n }\n else {\n ta <<= 6;\n bits -= 6;\n }\n }\n while ((out.length & 3) && !_noEquals) {\n out += \"=\";\n }\n return out;\n },\n /** Convert from a base64 string to a bitArray */\n toBits: function (str, _url) {\n str = str.replace(/\\s|=/g, '');\n var out = [], i, bits = 0, c = sjcl.codec.base64._chars, ta = 0, x;\n if (_url) {\n c = c.substr(0, 62) + '-_';\n }\n for (i = 0; i < str.length; i++) {\n x = c.indexOf(str.charAt(i));\n if (x < 0) {\n throw new sjcl.exception.invalid(\"this isn't base64!\");\n }\n if (bits > 26) {\n bits -= 26;\n out.push(ta ^ x >>> bits);\n ta = x << (32 - bits);\n }\n else {\n bits += 6;\n ta ^= x << (32 - bits);\n }\n }\n if (bits & 56) {\n out.push(sjcl.bitArray.partial(bits & 56, ta, 1));\n }\n return out;\n }\n};\nsjcl.codec.base64url = {\n fromBits: function (arr) { return sjcl.codec.base64.fromBits(arr, 1, 1); },\n toBits: function (str) { return sjcl.codec.base64.toBits(str, 1); }\n};\n/** @fileOverview Bit array codec implementations.\n *\n * @author Emily Stark\n * @author Mike Hamburg\n * @author Dan Boneh\n */\n/**\n * Arrays of bytes\n * @namespace\n */\nsjcl.codec.bytes = {\n /** Convert from a bitArray to an array of bytes. */\n fromBits: function (arr) {\n var out = [], bl = sjcl.bitArray.bitLength(arr), i, tmp;\n for (i = 0; i < bl / 8; i++) {\n if ((i & 3) === 0) {\n tmp = arr[i / 4];\n }\n out.push(tmp >>> 24);\n tmp <<= 8;\n }\n return out;\n },\n /** Convert from an array of bytes to a bitArray. */\n toBits: function (bytes) {\n var out = [], i, tmp = 0;\n for (i = 0; i < bytes.length; i++) {\n tmp = tmp << 8 | bytes[i];\n if ((i & 3) === 3) {\n out.push(tmp);\n tmp = 0;\n }\n }\n if (i & 3) {\n out.push(sjcl.bitArray.partial(8 * (i & 3), tmp));\n }\n return out;\n }\n};\n/** @fileOverview Javascript SHA-256 implementation.\n *\n * An older version of this implementation is available in the public\n * domain, but this one is (c) Emily Stark, Mike Hamburg, Dan Boneh,\n * Stanford University 2008-2010 and BSD-licensed for liability\n * reasons.\n *\n * Special thanks to Aldo Cortesi for pointing out several bugs in\n * this code.\n *\n * @author Emily Stark\n * @author Mike Hamburg\n * @author Dan Boneh\n */\n/**\n * Context for a SHA-256 operation in progress.\n * @constructor\n */\nsjcl.hash.sha256 = function (hash) {\n if (!this._key[0]) {\n this._precompute();\n }\n if (hash) {\n this._h = hash._h.slice(0);\n this._buffer = hash._buffer.slice(0);\n this._length = hash._length;\n }\n else {\n this.reset();\n }\n};\n/**\n * Hash a string or an array of words.\n * @static\n * @param {bitArray|String} data the data to hash.\n * @return {bitArray} The hash value, an array of 16 big-endian words.\n */\nsjcl.hash.sha256.hash = function (data) {\n return (new sjcl.hash.sha256()).update(data).finalize();\n};\nsjcl.hash.sha256.prototype = {\n /**\n * The hash's block size, in bits.\n * @constant\n */\n blockSize: 512,\n /**\n * Reset the hash state.\n * @return this\n */\n reset: function () {\n this._h = this._init.slice(0);\n this._buffer = [];\n this._length = 0;\n return this;\n },\n /**\n * Input several words to the hash.\n * @param {bitArray|String} data the data to hash.\n * @return this\n */\n update: function (data) {\n if (typeof data === \"string\") {\n data = sjcl.codec.utf8String.toBits(data);\n }\n var i, b = this._buffer = sjcl.bitArray.concat(this._buffer, data), ol = this._length, nl = this._length = ol + sjcl.bitArray.bitLength(data);\n if (nl > 9007199254740991) {\n throw new sjcl.exception.invalid(\"Cannot hash more than 2^53 - 1 bits\");\n }\n if (typeof Uint32Array !== 'undefined') {\n var c = new Uint32Array(b);\n var j = 0;\n for (i = 512 + ol - ((512 + ol) & 511); i <= nl; i += 512) {\n this._block(c.subarray(16 * j, 16 * (j + 1)));\n j += 1;\n }\n b.splice(0, 16 * j);\n }\n else {\n for (i = 512 + ol - ((512 + ol) & 511); i <= nl; i += 512) {\n this._block(b.splice(0, 16));\n }\n }\n return this;\n },\n /**\n * Complete hashing and output the hash value.\n * @return {bitArray} The hash value, an array of 8 big-endian words.\n */\n finalize: function () {\n var i, b = this._buffer, h = this._h;\n // Round out and push the buffer\n b = sjcl.bitArray.concat(b, [sjcl.bitArray.partial(1, 1)]);\n // Round out the buffer to a multiple of 16 words, less the 2 length words.\n for (i = b.length + 2; i & 15; i++) {\n b.push(0);\n }\n // append the length\n b.push(Math.floor(this._length / 0x100000000));\n b.push(this._length | 0);\n while (b.length) {\n this._block(b.splice(0, 16));\n }\n this.reset();\n return h;\n },\n /**\n * The SHA-256 initialization vector, to be precomputed.\n * @private\n */\n _init: [],\n /*\n _init:[0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19],\n */\n /**\n * The SHA-256 hash key, to be precomputed.\n * @private\n */\n _key: [],\n /*\n _key:\n [0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2],\n */\n /**\n * Function to precompute _init and _key.\n * @private\n */\n _precompute: function () {\n var i = 0, prime = 2, factor, isPrime;\n function frac(x) { return (x - Math.floor(x)) * 0x100000000 | 0; }\n for (; i < 64; prime++) {\n isPrime = true;\n for (factor = 2; factor * factor <= prime; factor++) {\n if (prime % factor === 0) {\n isPrime = false;\n break;\n }\n }\n if (isPrime) {\n if (i < 8) {\n this._init[i] = frac(Math.pow(prime, 1 / 2));\n }\n this._key[i] = frac(Math.pow(prime, 1 / 3));\n i++;\n }\n }\n },\n /**\n * Perform one cycle of SHA-256.\n * @param {Uint32Array|bitArray} w one block of words.\n * @private\n */\n _block: function (w) {\n var i, tmp, a, b, h = this._h, k = this._key, h0 = h[0], h1 = h[1], h2 = h[2], h3 = h[3], h4 = h[4], h5 = h[5], h6 = h[6], h7 = h[7];\n /* Rationale for placement of |0 :\n * If a value can overflow is original 32 bits by a factor of more than a few\n * million (2^23 ish), there is a possibility that it might overflow the\n * 53-bit mantissa and lose precision.\n *\n * To avoid this, we clamp back to 32 bits by |'ing with 0 on any value that\n * propagates around the loop, and on the hash state h[]. I don't believe\n * that the clamps on h4 and on h0 are strictly necessary, but it's close\n * (for h4 anyway), and better safe than sorry.\n *\n * The clamps on h[] are necessary for the output to be correct even in the\n * common case and for short inputs.\n */\n for (i = 0; i < 64; i++) {\n // load up the input word for this round\n if (i < 16) {\n tmp = w[i];\n }\n else {\n a = w[(i + 1) & 15];\n b = w[(i + 14) & 15];\n tmp = w[i & 15] = ((a >>> 7 ^ a >>> 18 ^ a >>> 3 ^ a << 25 ^ a << 14) +\n (b >>> 17 ^ b >>> 19 ^ b >>> 10 ^ b << 15 ^ b << 13) +\n w[i & 15] + w[(i + 9) & 15]) | 0;\n }\n tmp = (tmp + h7 + (h4 >>> 6 ^ h4 >>> 11 ^ h4 >>> 25 ^ h4 << 26 ^ h4 << 21 ^ h4 << 7) + (h6 ^ h4 & (h5 ^ h6)) + k[i]); // | 0;\n // shift register\n h7 = h6;\n h6 = h5;\n h5 = h4;\n h4 = h3 + tmp | 0;\n h3 = h2;\n h2 = h1;\n h1 = h0;\n h0 = (tmp + ((h1 & h2) ^ (h3 & (h1 ^ h2))) + (h1 >>> 2 ^ h1 >>> 13 ^ h1 >>> 22 ^ h1 << 30 ^ h1 << 19 ^ h1 << 10)) | 0;\n }\n h[0] = h[0] + h0 | 0;\n h[1] = h[1] + h1 | 0;\n h[2] = h[2] + h2 | 0;\n h[3] = h[3] + h3 | 0;\n h[4] = h[4] + h4 | 0;\n h[5] = h[5] + h5 | 0;\n h[6] = h[6] + h6 | 0;\n h[7] = h[7] + h7 | 0;\n }\n};\n/** @fileOverview CCM mode implementation.\n *\n * Special thanks to Roy Nicholson for pointing out a bug in our\n * implementation.\n *\n * @author Emily Stark\n * @author Mike Hamburg\n * @author Dan Boneh\n */\n/**\n * CTR mode with CBC MAC.\n * @namespace\n */\nsjcl.mode.ccm = {\n /** The name of the mode.\n * @constant\n */\n name: \"ccm\",\n _progressListeners: [],\n listenProgress: function (cb) {\n sjcl.mode.ccm._progressListeners.push(cb);\n },\n unListenProgress: function (cb) {\n var index = sjcl.mode.ccm._progressListeners.indexOf(cb);\n if (index > -1) {\n sjcl.mode.ccm._progressListeners.splice(index, 1);\n }\n },\n _callProgressListener: function (val) {\n var p = sjcl.mode.ccm._progressListeners.slice(), i;\n for (i = 0; i < p.length; i += 1) {\n p[i](val);\n }\n },\n /** Encrypt in CCM mode.\n * @static\n * @param {Object} prf The pseudorandom function. It must have a block size of 16 bytes.\n * @param {bitArray} plaintext The plaintext data.\n * @param {bitArray} iv The initialization value.\n * @param {bitArray} [adata=[]] The authenticated data.\n * @param {Number} [tlen=64] the desired tag length, in bits.\n * @return {bitArray} The encrypted data, an array of bytes.\n */\n encrypt: function (prf, plaintext, iv, adata, tlen) {\n var L, out = plaintext.slice(0), tag, w = sjcl.bitArray, ivl = w.bitLength(iv) / 8, ol = w.bitLength(out) / 8;\n tlen = tlen || 64;\n adata = adata || [];\n if (ivl < 7) {\n throw new sjcl.exception.invalid(\"ccm: iv must be at least 7 bytes\");\n }\n // compute the length of the length\n for (L = 2; L < 4 && ol >>> 8 * L; L++) { }\n if (L < 15 - ivl) {\n L = 15 - ivl;\n }\n iv = w.clamp(iv, 8 * (15 - L));\n // compute the tag\n tag = sjcl.mode.ccm._computeTag(prf, plaintext, iv, adata, tlen, L);\n // encrypt\n out = sjcl.mode.ccm._ctrMode(prf, out, iv, tag, tlen, L);\n return w.concat(out.data, out.tag);\n },\n /** Decrypt in CCM mode.\n * @static\n * @param {Object} prf The pseudorandom function. It must have a block size of 16 bytes.\n * @param {bitArray} ciphertext The ciphertext data.\n * @param {bitArray} iv The initialization value.\n * @param {bitArray} [adata=[]] adata The authenticated data.\n * @param {Number} [tlen=64] tlen the desired tag length, in bits.\n * @return {bitArray} The decrypted data.\n */\n decrypt: function (prf, ciphertext, iv, adata, tlen) {\n tlen = tlen || 64;\n adata = adata || [];\n var L, w = sjcl.bitArray, ivl = w.bitLength(iv) / 8, ol = w.bitLength(ciphertext), out = w.clamp(ciphertext, ol - tlen), tag = w.bitSlice(ciphertext, ol - tlen), tag2;\n ol = (ol - tlen) / 8;\n if (ivl < 7) {\n throw new sjcl.exception.invalid(\"ccm: iv must be at least 7 bytes\");\n }\n // compute the length of the length\n for (L = 2; L < 4 && ol >>> 8 * L; L++) { }\n if (L < 15 - ivl) {\n L = 15 - ivl;\n }\n iv = w.clamp(iv, 8 * (15 - L));\n // decrypt\n out = sjcl.mode.ccm._ctrMode(prf, out, iv, tag, tlen, L);\n // check the tag\n tag2 = sjcl.mode.ccm._computeTag(prf, out.data, iv, adata, tlen, L);\n if (!w.equal(out.tag, tag2)) {\n throw new sjcl.exception.corrupt(\"ccm: tag doesn't match\");\n }\n return out.data;\n },\n _macAdditionalData: function (prf, adata, iv, tlen, ol, L) {\n var mac, tmp, i, macData = [], w = sjcl.bitArray, xor = w._xor4;\n // mac the flags\n mac = [w.partial(8, (adata.length ? 1 << 6 : 0) | (tlen - 2) << 2 | L - 1)];\n // mac the iv and length\n mac = w.concat(mac, iv);\n mac[3] |= ol;\n mac = prf.encrypt(mac);\n if (adata.length) {\n // mac the associated data. start with its length...\n tmp = w.bitLength(adata) / 8;\n if (tmp <= 0xFEFF) {\n macData = [w.partial(16, tmp)];\n }\n else if (tmp <= 0xFFFFFFFF) {\n macData = w.concat([w.partial(16, 0xFFFE)], [tmp]);\n } // else ...\n // mac the data itself\n macData = w.concat(macData, adata);\n for (i = 0; i < macData.length; i += 4) {\n mac = prf.encrypt(xor(mac, macData.slice(i, i + 4).concat([0, 0, 0])));\n }\n }\n return mac;\n },\n /* Compute the (unencrypted) authentication tag, according to the CCM specification\n * @param {Object} prf The pseudorandom function.\n * @param {bitArray} plaintext The plaintext data.\n * @param {bitArray} iv The initialization value.\n * @param {bitArray} adata The authenticated data.\n * @param {Number} tlen the desired tag length, in bits.\n * @return {bitArray} The tag, but not yet encrypted.\n * @private\n */\n _computeTag: function (prf, plaintext, iv, adata, tlen, L) {\n // compute B[0]\n var mac, i, w = sjcl.bitArray, xor = w._xor4;\n tlen /= 8;\n // check tag length and message length\n if (tlen % 2 || tlen < 4 || tlen > 16) {\n throw new sjcl.exception.invalid(\"ccm: invalid tag length\");\n }\n if (adata.length > 0xFFFFFFFF || plaintext.length > 0xFFFFFFFF) {\n // I don't want to deal with extracting high words from doubles.\n throw new sjcl.exception.bug(\"ccm: can't deal with 4GiB or more data\");\n }\n mac = sjcl.mode.ccm._macAdditionalData(prf, adata, iv, tlen, w.bitLength(plaintext) / 8, L);\n // mac the plaintext\n for (i = 0; i < plaintext.length; i += 4) {\n mac = prf.encrypt(xor(mac, plaintext.slice(i, i + 4).concat([0, 0, 0])));\n }\n return w.clamp(mac, tlen * 8);\n },\n /** CCM CTR mode.\n * Encrypt or decrypt data and tag with the prf in CCM-style CTR mode.\n * May mutate its arguments.\n * @param {Object} prf The PRF.\n * @param {bitArray} data The data to be encrypted or decrypted.\n * @param {bitArray} iv The initialization vector.\n * @param {bitArray} tag The authentication tag.\n * @param {Number} tlen The length of th etag, in bits.\n * @param {Number} L The CCM L value.\n * @return {Object} An object with data and tag, the en/decryption of data and tag values.\n * @private\n */\n _ctrMode: function (prf, data, iv, tag, tlen, L) {\n var enc, i, w = sjcl.bitArray, xor = w._xor4, ctr, l = data.length, bl = w.bitLength(data), n = l / 50, p = n;\n // start the ctr\n ctr = w.concat([w.partial(8, L - 1)], iv).concat([0, 0, 0]).slice(0, 4);\n // en/decrypt the tag\n tag = w.bitSlice(xor(tag, prf.encrypt(ctr)), 0, tlen);\n // en/decrypt the data\n if (!l) {\n return { tag: tag, data: [] };\n }\n for (i = 0; i < l; i += 4) {\n if (i > n) {\n sjcl.mode.ccm._callProgressListener(i / l);\n n += p;\n }\n ctr[3]++;\n enc = prf.encrypt(ctr);\n data[i] ^= enc[0];\n data[i + 1] ^= enc[1];\n data[i + 2] ^= enc[2];\n data[i + 3] ^= enc[3];\n }\n return { tag: tag, data: w.clamp(data, bl) };\n }\n};\n/** @fileOverview HMAC implementation.\n *\n * @author Emily Stark\n * @author Mike Hamburg\n * @author Dan Boneh\n */\n/** HMAC with the specified hash function.\n * @constructor\n * @param {bitArray} key the key for HMAC.\n * @param {Object} [Hash=sjcl.hash.sha256] The hash function to use.\n */\nsjcl.misc.hmac = function (key, Hash) {\n this._hash = Hash = Hash || sjcl.hash.sha256;\n var exKey = [[], []], i, bs = Hash.prototype.blockSize / 32;\n this._baseHash = [new Hash(), new Hash()];\n if (key.length > bs) {\n key = Hash.hash(key);\n }\n for (i = 0; i < bs; i++) {\n exKey[0][i] = key[i] ^ 0x36363636;\n exKey[1][i] = key[i] ^ 0x5C5C5C5C;\n }\n this._baseHash[0].update(exKey[0]);\n this._baseHash[1].update(exKey[1]);\n this._resultHash = new Hash(this._baseHash[0]);\n};\n/** HMAC with the specified hash function. Also called encrypt since it's a prf.\n * @param {bitArray|String} data The data to mac.\n */\nsjcl.misc.hmac.prototype.encrypt = sjcl.misc.hmac.prototype.mac = function (data) {\n if (!this._updated) {\n this.update(data);\n return this.digest(data);\n }\n else {\n throw new sjcl.exception.invalid(\"encrypt on already updated hmac called!\");\n }\n};\nsjcl.misc.hmac.prototype.reset = function () {\n this._resultHash = new this._hash(this._baseHash[0]);\n this._updated = false;\n};\nsjcl.misc.hmac.prototype.update = function (data) {\n this._updated = true;\n this._resultHash.update(data);\n};\nsjcl.misc.hmac.prototype.digest = function () {\n var w = this._resultHash.finalize(), result = new (this._hash)(this._baseHash[1]).update(w).finalize();\n this.reset();\n return result;\n};\n/** @fileOverview Password-based key-derivation function, version 2.0.\n *\n * @author Emily Stark\n * @author Mike Hamburg\n * @author Dan Boneh\n */\n/** Password-Based Key-Derivation Function, version 2.0.\n *\n * Generate keys from passwords using PBKDF2-HMAC-SHA256.\n *\n * This is the method specified by RSA's PKCS #5 standard.\n *\n * @param {bitArray|String} password The password.\n * @param {bitArray|String} salt The salt. Should have lots of entropy.\n * @param {Number} [count=1000] The number of iterations. Higher numbers make the function slower but more secure.\n * @param {Number} [length] The length of the derived key. Defaults to the\n output size of the hash function.\n * @param {Object} [Prff=sjcl.misc.hmac] The pseudorandom function family.\n * @return {bitArray} the derived key.\n */\nsjcl.misc.pbkdf2 = function (password, salt, count, length, Prff) {\n count = count || 10000;\n if (length < 0 || count < 0) {\n throw new sjcl.exception.invalid(\"invalid params to pbkdf2\");\n }\n if (typeof password === \"string\") {\n password = sjcl.codec.utf8String.toBits(password);\n }\n if (typeof salt === \"string\") {\n salt = sjcl.codec.utf8String.toBits(salt);\n }\n Prff = Prff || sjcl.misc.hmac;\n var prf = new Prff(password), u, ui, i, j, k, out = [], b = sjcl.bitArray;\n for (k = 1; 32 * out.length < (length || 1); k++) {\n u = ui = prf.encrypt(b.concat(salt, [k]));\n for (i = 1; i < count; i++) {\n ui = prf.encrypt(ui);\n for (j = 0; j < ui.length; j++) {\n u[j] ^= ui[j];\n }\n }\n out = out.concat(u);\n }\n if (length) {\n out = b.clamp(out, length);\n }\n return out;\n};\n/** @fileOverview Random number generator.\n *\n * @author Emily Stark\n * @author Mike Hamburg\n * @author Dan Boneh\n * @author Michael Brooks\n * @author Steve Thomas\n */\n/**\n * @class Random number generator\n * @description\n * Use sjcl.random as a singleton for this class!\n *\n * This random number generator is a derivative of Ferguson and Schneier's\n * generator Fortuna. It collects entropy from various events into several\n * pools, implemented by streaming SHA-256 instances. It differs from\n * ordinary Fortuna in a few ways, though.\n *
\n *\n *\n * Most importantly, it has an entropy estimator. This is present because\n * there is a strong conflict here between making the generator available\n * as soon as possible, and making sure that it doesn't \"run on empty\".\n * In Fortuna, there is a saved state file, and the system is likely to have\n * time to warm up.\n *
\n *\n *\n * Second, because users are unlikely to stay on the page for very long,\n * and to speed startup time, the number of pools increases logarithmically:\n * a new pool is created when the previous one is actually used for a reseed.\n * This gives the same asymptotic guarantees as Fortuna, but gives more\n * entropy to early reseeds.\n *
\n *\n *\n * The entire mechanism here feels pretty klunky. Furthermore, there are\n * several improvements that should be made, including support for\n * dedicated cryptographic functions that may be present in some browsers;\n * state files in local storage; cookies containing randomness; etc. So\n * look for improvements in future versions.\n *
\n * @constructor\n */\nsjcl.prng = function (defaultParanoia) {\n /* private */\n this._pools = [new sjcl.hash.sha256()];\n this._poolEntropy = [0];\n this._reseedCount = 0;\n this._robins = {};\n this._eventId = 0;\n this._collectorIds = {};\n this._collectorIdNext = 0;\n this._strength = 0;\n this._poolStrength = 0;\n this._nextReseed = 0;\n this._key = [0, 0, 0, 0, 0, 0, 0, 0];\n this._counter = [0, 0, 0, 0];\n this._cipher = undefined;\n this._defaultParanoia = defaultParanoia;\n /* event listener stuff */\n this._collectorsStarted = false;\n this._callbacks = { progress: {}, seeded: {} };\n this._callbackI = 0;\n /* constants */\n this._NOT_READY = 0;\n this._READY = 1;\n this._REQUIRES_RESEED = 2;\n this._MAX_WORDS_PER_BURST = 65536;\n this._PARANOIA_LEVELS = [0, 48, 64, 96, 128, 192, 256, 384, 512, 768, 1024];\n this._MILLISECONDS_PER_RESEED = 30000;\n this._BITS_PER_RESEED = 80;\n};\nsjcl.prng.prototype = {\n /** Generate several random words, and return them in an array.\n * A word consists of 32 bits (4 bytes)\n * @param {Number} nwords The number of words to generate.\n */\n randomWords: function (nwords, paranoia) {\n var out = [], i, readiness = this.isReady(paranoia), g;\n if (readiness === this._NOT_READY) {\n throw new sjcl.exception.notReady(\"generator isn't seeded\");\n }\n else if (readiness & this._REQUIRES_RESEED) {\n this._reseedFromPools(!(readiness & this._READY));\n }\n for (i = 0; i < nwords; i += 4) {\n if ((i + 1) % this._MAX_WORDS_PER_BURST === 0) {\n this._gate();\n }\n g = this._gen4words();\n out.push(g[0], g[1], g[2], g[3]);\n }\n this._gate();\n return out.slice(0, nwords);\n },\n setDefaultParanoia: function (paranoia, allowZeroParanoia) {\n if (paranoia === 0 && allowZeroParanoia !== \"Setting paranoia=0 will ruin your security; use it only for testing\") {\n throw new sjcl.exception.invalid(\"Setting paranoia=0 will ruin your security; use it only for testing\");\n }\n this._defaultParanoia = paranoia;\n },\n /**\n * Add entropy to the pools.\n * @param data The entropic value. Should be a 32-bit integer, array of 32-bit integers, or string\n * @param {Number} estimatedEntropy The estimated entropy of data, in bits\n * @param {String} source The source of the entropy, eg \"mouse\"\n */\n addEntropy: function (data, estimatedEntropy, source) {\n source = source || \"user\";\n var id, i, tmp, t = (new Date()).valueOf(), robin = this._robins[source], oldReady = this.isReady(), err = 0, objName;\n id = this._collectorIds[source];\n if (id === undefined) {\n id = this._collectorIds[source] = this._collectorIdNext++;\n }\n if (robin === undefined) {\n robin = this._robins[source] = 0;\n }\n this._robins[source] = (this._robins[source] + 1) % this._pools.length;\n switch (typeof (data)) {\n case \"number\":\n if (estimatedEntropy === undefined) {\n estimatedEntropy = 1;\n }\n this._pools[robin].update([id, this._eventId++, 1, estimatedEntropy, t, 1, data | 0]);\n break;\n case \"object\":\n objName = Object.prototype.toString.call(data);\n if (objName === \"[object Uint32Array]\") {\n tmp = [];\n for (i = 0; i < data.length; i++) {\n tmp.push(data[i]);\n }\n data = tmp;\n }\n else {\n if (objName !== \"[object Array]\") {\n err = 1;\n }\n for (i = 0; i < data.length && !err; i++) {\n if (typeof (data[i]) !== \"number\") {\n err = 1;\n }\n }\n }\n if (!err) {\n if (estimatedEntropy === undefined) {\n /* horrible entropy estimator */\n estimatedEntropy = 0;\n for (i = 0; i < data.length; i++) {\n tmp = data[i];\n while (tmp > 0) {\n estimatedEntropy++;\n tmp = tmp >>> 1;\n }\n }\n }\n this._pools[robin].update([id, this._eventId++, 2, estimatedEntropy, t, data.length].concat(data));\n }\n break;\n case \"string\":\n if (estimatedEntropy === undefined) {\n /* English text has just over 1 bit per character of entropy.\n * But this might be HTML or something, and have far less\n * entropy than English... Oh well, let's just say one bit.\n */\n estimatedEntropy = data.length;\n }\n this._pools[robin].update([id, this._eventId++, 3, estimatedEntropy, t, data.length]);\n this._pools[robin].update(data);\n break;\n default:\n err = 1;\n }\n if (err) {\n throw new sjcl.exception.bug(\"random: addEntropy only supports number, array of numbers or string\");\n }\n /* record the new strength */\n this._poolEntropy[robin] += estimatedEntropy;\n this._poolStrength += estimatedEntropy;\n /* fire off events */\n if (oldReady === this._NOT_READY) {\n if (this.isReady() !== this._NOT_READY) {\n this._fireEvent(\"seeded\", Math.max(this._strength, this._poolStrength));\n }\n this._fireEvent(\"progress\", this.getProgress());\n }\n },\n /** Is the generator ready? */\n isReady: function (paranoia) {\n var entropyRequired = this._PARANOIA_LEVELS[(paranoia !== undefined) ? paranoia : this._defaultParanoia];\n if (this._strength && this._strength >= entropyRequired) {\n return (this._poolEntropy[0] > this._BITS_PER_RESEED && (new Date()).valueOf() > this._nextReseed) ?\n this._REQUIRES_RESEED | this._READY :\n this._READY;\n }\n else {\n return (this._poolStrength >= entropyRequired) ?\n this._REQUIRES_RESEED | this._NOT_READY :\n this._NOT_READY;\n }\n },\n /** Get the generator's progress toward readiness, as a fraction */\n getProgress: function (paranoia) {\n var entropyRequired = this._PARANOIA_LEVELS[paranoia ? paranoia : this._defaultParanoia];\n if (this._strength >= entropyRequired) {\n return 1.0;\n }\n else {\n return (this._poolStrength > entropyRequired) ?\n 1.0 :\n this._poolStrength / entropyRequired;\n }\n },\n /** start the built-in entropy collectors */\n startCollectors: function () {\n if (this._collectorsStarted) {\n return;\n }\n this._eventListener = {\n loadTimeCollector: this._bind(this._loadTimeCollector),\n mouseCollector: this._bind(this._mouseCollector),\n keyboardCollector: this._bind(this._keyboardCollector),\n accelerometerCollector: this._bind(this._accelerometerCollector),\n touchCollector: this._bind(this._touchCollector)\n };\n if (window.addEventListener) {\n window.addEventListener(\"load\", this._eventListener.loadTimeCollector, false);\n window.addEventListener(\"mousemove\", this._eventListener.mouseCollector, false);\n window.addEventListener(\"keypress\", this._eventListener.keyboardCollector, false);\n window.addEventListener(\"devicemotion\", this._eventListener.accelerometerCollector, false);\n window.addEventListener(\"touchmove\", this._eventListener.touchCollector, false);\n }\n else if (document.attachEvent) {\n document.attachEvent(\"onload\", this._eventListener.loadTimeCollector);\n document.attachEvent(\"onmousemove\", this._eventListener.mouseCollector);\n document.attachEvent(\"keypress\", this._eventListener.keyboardCollector);\n }\n else {\n throw new sjcl.exception.bug(\"can't attach event\");\n }\n this._collectorsStarted = true;\n },\n /** stop the built-in entropy collectors */\n stopCollectors: function () {\n if (!this._collectorsStarted) {\n return;\n }\n if (window.removeEventListener) {\n window.removeEventListener(\"load\", this._eventListener.loadTimeCollector, false);\n window.removeEventListener(\"mousemove\", this._eventListener.mouseCollector, false);\n window.removeEventListener(\"keypress\", this._eventListener.keyboardCollector, false);\n window.removeEventListener(\"devicemotion\", this._eventListener.accelerometerCollector, false);\n window.removeEventListener(\"touchmove\", this._eventListener.touchCollector, false);\n }\n else if (document.detachEvent) {\n document.detachEvent(\"onload\", this._eventListener.loadTimeCollector);\n document.detachEvent(\"onmousemove\", this._eventListener.mouseCollector);\n document.detachEvent(\"keypress\", this._eventListener.keyboardCollector);\n }\n this._collectorsStarted = false;\n },\n /* use a cookie to store entropy.\n useCookie: function (all_cookies) {\n throw new sjcl.exception.bug(\"random: useCookie is unimplemented\");\n },*/\n /** add an event listener for progress or seeded-ness. */\n addEventListener: function (name, callback) {\n this._callbacks[name][this._callbackI++] = callback;\n },\n /** remove an event listener for progress or seeded-ness */\n removeEventListener: function (name, cb) {\n var i, j, cbs = this._callbacks[name], jsTemp = [];\n /* I'm not sure if this is necessary; in C++, iterating over a\n * collection and modifying it at the same time is a no-no.\n */\n for (j in cbs) {\n if (cbs.hasOwnProperty(j) && cbs[j] === cb) {\n jsTemp.push(j);\n }\n }\n for (i = 0; i < jsTemp.length; i++) {\n j = jsTemp[i];\n delete cbs[j];\n }\n },\n _bind: function (func) {\n var that = this;\n return function () {\n func.apply(that, arguments);\n };\n },\n /** Generate 4 random words, no reseed, no gate.\n * @private\n */\n _gen4words: function () {\n for (var i = 0; i < 4; i++) {\n this._counter[i] = this._counter[i] + 1 | 0;\n if (this._counter[i]) {\n break;\n }\n }\n return this._cipher.encrypt(this._counter);\n },\n /* Rekey the AES instance with itself after a request, or every _MAX_WORDS_PER_BURST words.\n * @private\n */\n _gate: function () {\n this._key = this._gen4words().concat(this._gen4words());\n this._cipher = new sjcl.cipher.aes(this._key);\n },\n /** Reseed the generator with the given words\n * @private\n */\n _reseed: function (seedWords) {\n this._key = sjcl.hash.sha256.hash(this._key.concat(seedWords));\n this._cipher = new sjcl.cipher.aes(this._key);\n for (var i = 0; i < 4; i++) {\n this._counter[i] = this._counter[i] + 1 | 0;\n if (this._counter[i]) {\n break;\n }\n }\n },\n /** reseed the data from the entropy pools\n * @param full If set, use all the entropy pools in the reseed.\n */\n _reseedFromPools: function (full) {\n var reseedData = [], strength = 0, i;\n this._nextReseed = reseedData[0] =\n (new Date()).valueOf() + this._MILLISECONDS_PER_RESEED;\n for (i = 0; i < 16; i++) {\n /* On some browsers, this is cryptographically random. So we might\n * as well toss it in the pot and stir...\n */\n reseedData.push(Math.random() * 0x100000000 | 0);\n }\n for (i = 0; i < this._pools.length; i++) {\n reseedData = reseedData.concat(this._pools[i].finalize());\n strength += this._poolEntropy[i];\n this._poolEntropy[i] = 0;\n if (!full && (this._reseedCount & (1 << i))) {\n break;\n }\n }\n /* if we used the last pool, push a new one onto the stack */\n if (this._reseedCount >= 1 << this._pools.length) {\n this._pools.push(new sjcl.hash.sha256());\n this._poolEntropy.push(0);\n }\n /* how strong was this reseed? */\n this._poolStrength -= strength;\n if (strength > this._strength) {\n this._strength = strength;\n }\n this._reseedCount++;\n this._reseed(reseedData);\n },\n _keyboardCollector: function () {\n this._addCurrentTimeToEntropy(1);\n },\n _mouseCollector: function (ev) {\n var x, y;\n try {\n x = ev.x || ev.clientX || ev.offsetX || 0;\n y = ev.y || ev.clientY || ev.offsetY || 0;\n }\n catch (err) {\n // Event originated from a secure element. No mouse position available.\n x = 0;\n y = 0;\n }\n if (x != 0 && y != 0) {\n this.addEntropy([x, y], 2, \"mouse\");\n }\n this._addCurrentTimeToEntropy(0);\n },\n _touchCollector: function (ev) {\n var touch = ev.touches[0] || ev.changedTouches[0];\n var x = touch.pageX || touch.clientX, y = touch.pageY || touch.clientY;\n this.addEntropy([x, y], 1, \"touch\");\n this._addCurrentTimeToEntropy(0);\n },\n _loadTimeCollector: function () {\n this._addCurrentTimeToEntropy(2);\n },\n _addCurrentTimeToEntropy: function (estimatedEntropy) {\n if (typeof window !== 'undefined' && window.performance && typeof window.performance.now === \"function\") {\n //how much entropy do we want to add here?\n this.addEntropy(window.performance.now(), estimatedEntropy, \"loadtime\");\n }\n else {\n this.addEntropy((new Date()).valueOf(), estimatedEntropy, \"loadtime\");\n }\n },\n _accelerometerCollector: function (ev) {\n var ac = ev.accelerationIncludingGravity.x || ev.accelerationIncludingGravity.y || ev.accelerationIncludingGravity.z;\n if (window.orientation) {\n var or = window.orientation;\n if (typeof or === \"number\") {\n this.addEntropy(or, 1, \"accelerometer\");\n }\n }\n if (ac) {\n this.addEntropy(ac, 2, \"accelerometer\");\n }\n this._addCurrentTimeToEntropy(0);\n },\n _fireEvent: function (name, arg) {\n var j, cbs = sjcl.random._callbacks[name], cbsTemp = [];\n /* TODO: there is a race condition between removing collectors and firing them */\n /* I'm not sure if this is necessary; in C++, iterating over a\n * collection and modifying it at the same time is a no-no.\n */\n for (j in cbs) {\n if (cbs.hasOwnProperty(j)) {\n cbsTemp.push(cbs[j]);\n }\n }\n for (j = 0; j < cbsTemp.length; j++) {\n cbsTemp[j](arg);\n }\n }\n};\n/** an instance for the prng.\n* @see sjcl.prng\n*/\nsjcl.random = new sjcl.prng(6);\n(function () {\n // function for getting nodejs crypto module. catches and ignores errors.\n function getCryptoModule() {\n try {\n return require('crypto');\n }\n catch (e) {\n return null;\n }\n }\n try {\n var buf, crypt, ab;\n // get cryptographically strong entropy depending on runtime environment\n if (typeof module !== 'undefined' && module.exports && (crypt = getCryptoModule()) && crypt.randomBytes) {\n buf = crypt.randomBytes(1024 / 8);\n buf = new Uint32Array(new Uint8Array(buf).buffer);\n sjcl.random.addEntropy(buf, 1024, \"crypto.randomBytes\");\n }\n else if (typeof window !== 'undefined' && typeof Uint32Array !== 'undefined') {\n ab = new Uint32Array(32);\n if (window.crypto && window.crypto.getRandomValues) {\n window.crypto.getRandomValues(ab);\n }\n else if (window.msCrypto && window.msCrypto.getRandomValues) {\n window.msCrypto.getRandomValues(ab);\n }\n else {\n return;\n }\n // get cryptographically strong entropy in Webkit\n sjcl.random.addEntropy(ab, 1024, \"crypto.getRandomValues\");\n }\n else {\n // no getRandomValues :-(\n }\n }\n catch (e) {\n if (typeof window !== 'undefined' && window.console) {\n console.log(\"There was an error collecting entropy from the browser:\");\n console.log(e);\n //we do not want the library to fail due to randomness not being maintained.\n }\n }\n}());\n/** @fileOverview Convenience functions centered around JSON encapsulation.\n *\n * @author Emily Stark\n * @author Mike Hamburg\n * @author Dan Boneh\n */\n/**\n * JSON encapsulation\n * @namespace\n */\nsjcl.json = {\n /** Default values for encryption */\n defaults: { v: 1, iter: 10000, ks: 128, ts: 64, mode: \"ccm\", adata: \"\", cipher: \"aes\" },\n /** Simple encryption function.\n * @param {String|bitArray} password The password or key.\n * @param {String} plaintext The data to encrypt.\n * @param {Object} [params] The parameters including tag, iv and salt.\n * @param {Object} [rp] A returned version with filled-in parameters.\n * @return {Object} The cipher raw data.\n * @throws {sjcl.exception.invalid} if a parameter is invalid.\n */\n _encrypt: function (password, plaintext, params, rp) {\n params = params || {};\n rp = rp || {};\n var j = sjcl.json, p = j._add({ iv: sjcl.random.randomWords(4, 0) }, j.defaults), tmp, prp, adata;\n j._add(p, params);\n adata = p.adata;\n if (typeof p.salt === \"string\") {\n p.salt = sjcl.codec.base64.toBits(p.salt);\n }\n if (typeof p.iv === \"string\") {\n p.iv = sjcl.codec.base64.toBits(p.iv);\n }\n if (!sjcl.mode[p.mode] ||\n !sjcl.cipher[p.cipher] ||\n (typeof password === \"string\" && p.iter <= 100) ||\n (p.ts !== 64 && p.ts !== 96 && p.ts !== 128) ||\n (p.ks !== 128 && p.ks !== 192 && p.ks !== 256) ||\n (p.iv.length < 2 || p.iv.length > 4)) {\n throw new sjcl.exception.invalid(\"json encrypt: invalid parameters\");\n }\n if (typeof password === \"string\") {\n tmp = sjcl.misc.cachedPbkdf2(password, p);\n password = tmp.key.slice(0, p.ks / 32);\n p.salt = tmp.salt;\n }\n else if (sjcl.ecc && password instanceof sjcl.ecc.elGamal.publicKey) {\n tmp = password.kem();\n p.kemtag = tmp.tag;\n password = tmp.key.slice(0, p.ks / 32);\n }\n if (typeof plaintext === \"string\") {\n plaintext = sjcl.codec.utf8String.toBits(plaintext);\n }\n if (typeof adata === \"string\") {\n p.adata = adata = sjcl.codec.utf8String.toBits(adata);\n }\n prp = new sjcl.cipher[p.cipher](password);\n /* return the json data */\n j._add(rp, p);\n rp.key = password;\n /* do the encryption */\n if (p.mode === \"ccm\" && sjcl.arrayBuffer && sjcl.arrayBuffer.ccm && plaintext instanceof ArrayBuffer) {\n p.ct = sjcl.arrayBuffer.ccm.encrypt(prp, plaintext, p.iv, adata, p.ts);\n }\n else {\n p.ct = sjcl.mode[p.mode].encrypt(prp, plaintext, p.iv, adata, p.ts);\n }\n //return j.encode(j._subtract(p, j.defaults));\n return p;\n },\n /** Simple encryption function.\n * @param {String|bitArray} password The password or key.\n * @param {String} plaintext The data to encrypt.\n * @param {Object} [params] The parameters including tag, iv and salt.\n * @param {Object} [rp] A returned version with filled-in parameters.\n * @return {String} The ciphertext serialized data.\n * @throws {sjcl.exception.invalid} if a parameter is invalid.\n */\n encrypt: function (password, plaintext, params, rp) {\n var j = sjcl.json, p = j._encrypt.apply(j, arguments);\n return j.encode(p);\n },\n /** Simple decryption function.\n * @param {String|bitArray} password The password or key.\n * @param {Object} ciphertext The cipher raw data to decrypt.\n * @param {Object} [params] Additional non-default parameters.\n * @param {Object} [rp] A returned object with filled parameters.\n * @return {String} The plaintext.\n * @throws {sjcl.exception.invalid} if a parameter is invalid.\n * @throws {sjcl.exception.corrupt} if the ciphertext is corrupt.\n */\n _decrypt: function (password, ciphertext, params, rp) {\n params = params || {};\n rp = rp || {};\n var j = sjcl.json, p = j._add(j._add(j._add({}, j.defaults), ciphertext), params, true), ct, tmp, prp, adata = p.adata;\n if (typeof p.salt === \"string\") {\n p.salt = sjcl.codec.base64.toBits(p.salt);\n }\n if (typeof p.iv === \"string\") {\n p.iv = sjcl.codec.base64.toBits(p.iv);\n }\n if (!sjcl.mode[p.mode] ||\n !sjcl.cipher[p.cipher] ||\n (typeof password === \"string\" && p.iter <= 100) ||\n (p.ts !== 64 && p.ts !== 96 && p.ts !== 128) ||\n (p.ks !== 128 && p.ks !== 192 && p.ks !== 256) ||\n (!p.iv) ||\n (p.iv.length < 2 || p.iv.length > 4)) {\n throw new sjcl.exception.invalid(\"json decrypt: invalid parameters\");\n }\n if (typeof password === \"string\") {\n tmp = sjcl.misc.cachedPbkdf2(password, p);\n password = tmp.key.slice(0, p.ks / 32);\n p.salt = tmp.salt;\n }\n else if (sjcl.ecc && password instanceof sjcl.ecc.elGamal.secretKey) {\n password = password.unkem(sjcl.codec.base64.toBits(p.kemtag)).slice(0, p.ks / 32);\n }\n if (typeof adata === \"string\") {\n adata = sjcl.codec.utf8String.toBits(adata);\n }\n prp = new sjcl.cipher[p.cipher](password);\n /* do the decryption */\n if (p.mode === \"ccm\" && sjcl.arrayBuffer && sjcl.arrayBuffer.ccm && p.ct instanceof ArrayBuffer) {\n ct = sjcl.arrayBuffer.ccm.decrypt(prp, p.ct, p.iv, p.tag, adata, p.ts);\n }\n else {\n ct = sjcl.mode[p.mode].decrypt(prp, p.ct, p.iv, adata, p.ts);\n }\n /* return the json data */\n j._add(rp, p);\n rp.key = password;\n if (params.raw === 1) {\n return ct;\n }\n else {\n return sjcl.codec.utf8String.fromBits(ct);\n }\n },\n /** Simple decryption function.\n * @param {String|bitArray} password The password or key.\n * @param {String} ciphertext The ciphertext to decrypt.\n * @param {Object} [params] Additional non-default parameters.\n * @param {Object} [rp] A returned object with filled parameters.\n * @return {String} The plaintext.\n * @throws {sjcl.exception.invalid} if a parameter is invalid.\n * @throws {sjcl.exception.corrupt} if the ciphertext is corrupt.\n */\n decrypt: function (password, ciphertext, params, rp) {\n var j = sjcl.json;\n return j._decrypt(password, j.decode(ciphertext), params, rp);\n },\n /** Encode a flat structure into a JSON string.\n * @param {Object} obj The structure to encode.\n * @return {String} A JSON string.\n * @throws {sjcl.exception.invalid} if obj has a non-alphanumeric property.\n * @throws {sjcl.exception.bug} if a parameter has an unsupported type.\n */\n encode: function (obj) {\n var i, out = '{', comma = '';\n for (i in obj) {\n if (obj.hasOwnProperty(i)) {\n if (!i.match(/^[a-z0-9]+$/i)) {\n throw new sjcl.exception.invalid(\"json encode: invalid property name\");\n }\n out += comma + '\"' + i + '\":';\n comma = ',';\n switch (typeof obj[i]) {\n case 'number':\n case 'boolean':\n out += obj[i];\n break;\n case 'string':\n out += '\"' + escape(obj[i]) + '\"';\n break;\n case 'object':\n out += '\"' + sjcl.codec.base64.fromBits(obj[i], 0) + '\"';\n break;\n default:\n throw new sjcl.exception.bug(\"json encode: unsupported type\");\n }\n }\n }\n return out + '}';\n },\n /** Decode a simple (flat) JSON string into a structure. The ciphertext,\n * adata, salt and iv will be base64-decoded.\n * @param {String} str The string.\n * @return {Object} The decoded structure.\n * @throws {sjcl.exception.invalid} if str isn't (simple) JSON.\n */\n decode: function (str) {\n str = str.replace(/\\s/g, '');\n if (!str.match(/^\\{.*\\}$/)) {\n throw new sjcl.exception.invalid(\"json decode: this isn't json!\");\n }\n var a = str.replace(/^\\{|\\}$/g, '').split(/,/), out = {}, i, m;\n for (i = 0; i < a.length; i++) {\n if (!(m = a[i].match(/^\\s*(?:([\"']?)([a-z][a-z0-9]*)\\1)\\s*:\\s*(?:(-?\\d+)|\"([a-z0-9+\\/%*_.@=\\-]*)\"|(true|false))$/i))) {\n throw new sjcl.exception.invalid(\"json decode: this isn't json!\");\n }\n if (m[3] != null) {\n out[m[2]] = parseInt(m[3], 10);\n }\n else if (m[4] != null) {\n out[m[2]] = m[2].match(/^(ct|adata|salt|iv)$/) ? sjcl.codec.base64.toBits(m[4]) : unescape(m[4]);\n }\n else if (m[5] != null) {\n out[m[2]] = m[5] === 'true';\n }\n }\n return out;\n },\n /** Insert all elements of src into target, modifying and returning target.\n * @param {Object} target The object to be modified.\n * @param {Object} src The object to pull data from.\n * @param {boolean} [requireSame=false] If true, throw an exception if any field of target differs from corresponding field of src.\n * @return {Object} target.\n * @private\n */\n _add: function (target, src, requireSame) {\n if (target === undefined) {\n target = {};\n }\n if (src === undefined) {\n return target;\n }\n var i;\n for (i in src) {\n if (src.hasOwnProperty(i)) {\n if (requireSame && target[i] !== undefined && target[i] !== src[i]) {\n throw new sjcl.exception.invalid(\"required parameter overridden\");\n }\n target[i] = src[i];\n }\n }\n return target;\n },\n /** Remove all elements of minus from plus. Does not modify plus.\n * @private\n */\n _subtract: function (plus, minus) {\n var out = {}, i;\n for (i in plus) {\n if (plus.hasOwnProperty(i) && plus[i] !== minus[i]) {\n out[i] = plus[i];\n }\n }\n return out;\n },\n /** Return only the specified elements of src.\n * @private\n */\n _filter: function (src, filter) {\n var out = {}, i;\n for (i = 0; i < filter.length; i++) {\n if (src[filter[i]] !== undefined) {\n out[filter[i]] = src[filter[i]];\n }\n }\n return out;\n }\n};\n/** Simple encryption function; convenient shorthand for sjcl.json.encrypt.\n * @param {String|bitArray} password The password or key.\n * @param {String} plaintext The data to encrypt.\n * @param {Object} [params] The parameters including tag, iv and salt.\n * @param {Object} [rp] A returned version with filled-in parameters.\n * @return {String} The ciphertext.\n */\nsjcl.encrypt = sjcl.json.encrypt;\n/** Simple decryption function; convenient shorthand for sjcl.json.decrypt.\n * @param {String|bitArray} password The password or key.\n * @param {String} ciphertext The ciphertext to decrypt.\n * @param {Object} [params] Additional non-default parameters.\n * @param {Object} [rp] A returned object with filled parameters.\n * @return {String} The plaintext.\n */\nsjcl.decrypt = sjcl.json.decrypt;\n/** The cache for cachedPbkdf2.\n * @private\n */\nsjcl.misc._pbkdf2Cache = {};\n/** Cached PBKDF2 key derivation.\n * @param {String} password The password.\n * @param {Object} [obj] The derivation params (iteration count and optional salt).\n * @return {Object} The derived data in key, the salt in salt.\n */\nsjcl.misc.cachedPbkdf2 = function (password, obj) {\n var cache = sjcl.misc._pbkdf2Cache, c, cp, str, salt, iter;\n obj = obj || {};\n iter = obj.iter || 1000;\n /* open the cache for this password and iteration count */\n cp = cache[password] = cache[password] || {};\n c = cp[iter] = cp[iter] || { firstSalt: (obj.salt && obj.salt.length) ?\n obj.salt.slice(0) : sjcl.random.randomWords(2, 0) };\n salt = (obj.salt === undefined) ? c.firstSalt : obj.salt;\n c[salt] = c[salt] || sjcl.misc.pbkdf2(password, salt, obj.iter);\n return { key: c[salt].slice(0), salt: salt.slice(0) };\n};\n// Thanks to Colin McRae and Jonathan Burns of ionic security\n// for reporting and fixing two bugs in this file!\n/**\n * Constructs a new bignum from another bignum, a number or a hex string.\n * @constructor\n */\nsjcl.bn = function (it) {\n this.initWith(it);\n};\nsjcl.bn.prototype = {\n radix: 24,\n maxMul: 8,\n _class: sjcl.bn,\n copy: function () {\n return new this._class(this);\n },\n /**\n * Initializes this with it, either as a bn, a number, or a hex string.\n */\n initWith: function (it) {\n var i = 0, k;\n switch (typeof it) {\n case \"object\":\n this.limbs = it.limbs.slice(0);\n break;\n case \"number\":\n this.limbs = [it];\n this.normalize();\n break;\n case \"string\":\n it = it.replace(/^0x/, '');\n this.limbs = [];\n // hack\n k = this.radix / 4;\n for (i = 0; i < it.length; i += k) {\n this.limbs.push(parseInt(it.substring(Math.max(it.length - i - k, 0), it.length - i), 16));\n }\n break;\n default:\n this.limbs = [0];\n }\n return this;\n },\n /**\n * Returns true if \"this\" and \"that\" are equal. Calls fullReduce().\n * Equality test is in constant time.\n */\n equals: function (that) {\n if (typeof that === \"number\") {\n that = new this._class(that);\n }\n var difference = 0, i;\n this.fullReduce();\n that.fullReduce();\n for (i = 0; i < this.limbs.length || i < that.limbs.length; i++) {\n difference |= this.getLimb(i) ^ that.getLimb(i);\n }\n return (difference === 0);\n },\n /**\n * Get the i'th limb of this, zero if i is too large.\n */\n getLimb: function (i) {\n return (i >= this.limbs.length) ? 0 : this.limbs[i];\n },\n /**\n * Constant time comparison function.\n * Returns 1 if this >= that, or zero otherwise.\n */\n greaterEquals: function (that) {\n if (typeof that === \"number\") {\n that = new this._class(that);\n }\n var less = 0, greater = 0, i, a, b;\n i = Math.max(this.limbs.length, that.limbs.length) - 1;\n for (; i >= 0; i--) {\n a = this.getLimb(i);\n b = that.getLimb(i);\n greater |= (b - a) & ~less;\n less |= (a - b) & ~greater;\n }\n return (greater | ~less) >>> 31;\n },\n /**\n * Convert to a hex string.\n */\n toString: function () {\n this.fullReduce();\n var out = \"\", i, s, l = this.limbs;\n for (i = 0; i < this.limbs.length; i++) {\n s = l[i].toString(16);\n while (i < this.limbs.length - 1 && s.length < 6) {\n s = \"0\" + s;\n }\n out = s + out;\n }\n return \"0x\" + out;\n },\n /** this += that. Does not normalize. */\n addM: function (that) {\n if (typeof (that) !== \"object\") {\n that = new this._class(that);\n }\n var i, l = this.limbs, ll = that.limbs;\n for (i = l.length; i < ll.length; i++) {\n l[i] = 0;\n }\n for (i = 0; i < ll.length; i++) {\n l[i] += ll[i];\n }\n return this;\n },\n /** this *= 2. Requires normalized; ends up normalized. */\n doubleM: function () {\n var i, carry = 0, tmp, r = this.radix, m = this.radixMask, l = this.limbs;\n for (i = 0; i < l.length; i++) {\n tmp = l[i];\n tmp = tmp + tmp + carry;\n l[i] = tmp & m;\n carry = tmp >> r;\n }\n if (carry) {\n l.push(carry);\n }\n return this;\n },\n /** this /= 2, rounded down. Requires normalized; ends up normalized. */\n halveM: function () {\n var i, carry = 0, tmp, r = this.radix, l = this.limbs;\n for (i = l.length - 1; i >= 0; i--) {\n tmp = l[i];\n l[i] = (tmp + carry) >> 1;\n carry = (tmp & 1) << r;\n }\n if (!l[l.length - 1]) {\n l.pop();\n }\n return this;\n },\n /** this -= that. Does not normalize. */\n subM: function (that) {\n if (typeof (that) !== \"object\") {\n that = new this._class(that);\n }\n var i, l = this.limbs, ll = that.limbs;\n for (i = l.length; i < ll.length; i++) {\n l[i] = 0;\n }\n for (i = 0; i < ll.length; i++) {\n l[i] -= ll[i];\n }\n return this;\n },\n mod: function (that) {\n var neg = !this.greaterEquals(new sjcl.bn(0));\n that = new sjcl.bn(that).normalize(); // copy before we begin\n var out = new sjcl.bn(this).normalize(), ci = 0;\n if (neg)\n out = (new sjcl.bn(0)).subM(out).normalize();\n for (; out.greaterEquals(that); ci++) {\n that.doubleM();\n }\n if (neg)\n out = that.sub(out).normalize();\n for (; ci > 0; ci--) {\n that.halveM();\n if (out.greaterEquals(that)) {\n out.subM(that).normalize();\n }\n }\n return out.trim();\n },\n /** return inverse mod prime p. p must be odd. Binary extended Euclidean algorithm mod p. */\n inverseMod: function (p) {\n var a = new sjcl.bn(1), b = new sjcl.bn(0), x = new sjcl.bn(this), y = new sjcl.bn(p), tmp, i, nz = 1;\n if (!(p.limbs[0] & 1)) {\n throw (new sjcl.exception.invalid(\"inverseMod: p must be odd\"));\n }\n // invariant: y is odd\n do {\n if (x.limbs[0] & 1) {\n if (!x.greaterEquals(y)) {\n // x < y; swap everything\n tmp = x;\n x = y;\n y = tmp;\n tmp = a;\n a = b;\n b = tmp;\n }\n x.subM(y);\n x.normalize();\n if (!a.greaterEquals(b)) {\n a.addM(p);\n }\n a.subM(b);\n }\n // cut everything in half\n x.halveM();\n if (a.limbs[0] & 1) {\n a.addM(p);\n }\n a.normalize();\n a.halveM();\n // check for termination: x ?= 0\n for (i = nz = 0; i < x.limbs.length; i++) {\n nz |= x.limbs[i];\n }\n } while (nz);\n if (!y.equals(1)) {\n throw (new sjcl.exception.invalid(\"inverseMod: p and x must be relatively prime\"));\n }\n return b;\n },\n /** this + that. Does not normalize. */\n add: function (that) {\n return this.copy().addM(that);\n },\n /** this - that. Does not normalize. */\n sub: function (that) {\n return this.copy().subM(that);\n },\n /** this * that. Normalizes and reduces. */\n mul: function (that) {\n if (typeof (that) === \"number\") {\n that = new this._class(that);\n }\n else {\n that.normalize();\n }\n this.normalize();\n var i, j, a = this.limbs, b = that.limbs, al = a.length, bl = b.length, out = new this._class(), c = out.limbs, ai, ii = this.maxMul;\n for (i = 0; i < this.limbs.length + that.limbs.length + 1; i++) {\n c[i] = 0;\n }\n for (i = 0; i < al; i++) {\n ai = a[i];\n for (j = 0; j < bl; j++) {\n c[i + j] += ai * b[j];\n }\n if (!--ii) {\n ii = this.maxMul;\n out.cnormalize();\n }\n }\n return out.cnormalize().reduce();\n },\n /** this ^ 2. Normalizes and reduces. */\n square: function () {\n return this.mul(this);\n },\n /** this ^ n. Uses square-and-multiply. Normalizes and reduces. */\n power: function (l) {\n l = new sjcl.bn(l).normalize().trim().limbs;\n var i, j, out = new this._class(1), pow = this;\n for (i = 0; i < l.length; i++) {\n for (j = 0; j < this.radix; j++) {\n if (l[i] & (1 << j)) {\n out = out.mul(pow);\n }\n if (i == (l.length - 1) && l[i] >> (j + 1) == 0) {\n break;\n }\n pow = pow.square();\n }\n }\n return out;\n },\n /** this * that mod N */\n mulmod: function (that, N) {\n return this.mod(N).mul(that.mod(N)).mod(N);\n },\n /** this ^ x mod N */\n powermod: function (x, N) {\n x = new sjcl.bn(x);\n N = new sjcl.bn(N);\n // Jump to montpowermod if possible.\n if ((N.limbs[0] & 1) == 1) {\n var montOut = this.montpowermod(x, N);\n if (montOut != false) {\n return montOut;\n } // else go to slow powermod\n }\n var i, j, l = x.normalize().trim().limbs, out = new this._class(1), pow = this;\n for (i = 0; i < l.length; i++) {\n for (j = 0; j < this.radix; j++) {\n if (l[i] & (1 << j)) {\n out = out.mulmod(pow, N);\n }\n if (i == (l.length - 1) && l[i] >> (j + 1) == 0) {\n break;\n }\n pow = pow.mulmod(pow, N);\n }\n }\n return out;\n },\n /** this ^ x mod N with Montomery reduction */\n montpowermod: function (x, N) {\n x = new sjcl.bn(x).normalize().trim();\n N = new sjcl.bn(N);\n var i, j, radix = this.radix, out = new this._class(1), pow = this.copy();\n // Generate R as a cap of N.\n var R, s, wind, bitsize = x.bitLength();\n R = new sjcl.bn({\n limbs: N.copy().normalize().trim().limbs.map(function () { return 0; })\n });\n for (s = this.radix; s > 0; s--) {\n if (((N.limbs[N.limbs.length - 1] >> s) & 1) == 1) {\n R.limbs[R.limbs.length - 1] = 1 << s;\n break;\n }\n }\n // Calculate window size as a function of the exponent's size.\n if (bitsize == 0) {\n return this;\n }\n else if (bitsize < 18) {\n wind = 1;\n }\n else if (bitsize < 48) {\n wind = 3;\n }\n else if (bitsize < 144) {\n wind = 4;\n }\n else if (bitsize < 768) {\n wind = 5;\n }\n else {\n wind = 6;\n }\n // Find R' and N' such that R * R' - N * N' = 1.\n var RR = R.copy(), NN = N.copy(), RP = new sjcl.bn(1), NP = new sjcl.bn(0), RT = R.copy();\n while (RT.greaterEquals(1)) {\n RT.halveM();\n if ((RP.limbs[0] & 1) == 0) {\n RP.halveM();\n NP.halveM();\n }\n else {\n RP.addM(NN);\n RP.halveM();\n NP.halveM();\n NP.addM(RR);\n }\n }\n RP = RP.normalize();\n NP = NP.normalize();\n RR.doubleM();\n var R2 = RR.mulmod(RR, N);\n // Check whether the invariant holds.\n // If it doesn't, we can't use Montgomery reduction on this modulus.\n if (!RR.mul(RP).sub(N.mul(NP)).equals(1)) {\n return false;\n }\n var montIn = function (c) { return montMul(c, R2); }, montMul = function (a, b) {\n // Standard Montgomery reduction\n var k, ab, right, abBar, mask = (1 << (s + 1)) - 1;\n ab = a.mul(b);\n right = ab.mul(NP);\n right.limbs = right.limbs.slice(0, R.limbs.length);\n if (right.limbs.length == R.limbs.length) {\n right.limbs[R.limbs.length - 1] &= mask;\n }\n right = right.mul(N);\n abBar = ab.add(right).normalize().trim();\n abBar.limbs = abBar.limbs.slice(R.limbs.length - 1);\n // Division. Equivelent to calling *.halveM() s times.\n for (k = 0; k < abBar.limbs.length; k++) {\n if (k > 0) {\n abBar.limbs[k - 1] |= (abBar.limbs[k] & mask) << (radix - s - 1);\n }\n abBar.limbs[k] = abBar.limbs[k] >> (s + 1);\n }\n if (abBar.greaterEquals(N)) {\n abBar.subM(N);\n }\n return abBar;\n }, montOut = function (c) { return montMul(c, 1); };\n pow = montIn(pow);\n out = montIn(out);\n // Sliding-Window Exponentiation (HAC 14.85)\n var h, precomp = {}, cap = (1 << (wind - 1)) - 1;\n precomp[1] = pow.copy();\n precomp[2] = montMul(pow, pow);\n for (h = 1; h <= cap; h++) {\n precomp[(2 * h) + 1] = montMul(precomp[(2 * h) - 1], precomp[2]);\n }\n var getBit = function (exp, i) {\n var off = i % exp.radix;\n return (exp.limbs[Math.floor(i / exp.radix)] & (1 << off)) >> off;\n };\n for (i = x.bitLength() - 1; i >= 0;) {\n if (getBit(x, i) == 0) {\n // If the next bit is zero:\n // Square, move forward one bit.\n out = montMul(out, out);\n i = i - 1;\n }\n else {\n // If the next bit is one:\n // Find the longest sequence of bits after this one, less than `wind`\n // bits long, that ends with a 1. Convert the sequence into an\n // integer and look up the pre-computed value to add.\n var l = i - wind + 1;\n while (getBit(x, l) == 0) {\n l++;\n }\n var indx = 0;\n for (j = l; j <= i; j++) {\n indx += getBit(x, j) << (j - l);\n out = montMul(out, out);\n }\n out = montMul(out, precomp[indx]);\n i = l - 1;\n }\n }\n return montOut(out);\n },\n trim: function () {\n var l = this.limbs, p;\n do {\n p = l.pop();\n } while (l.length && p === 0);\n l.push(p);\n return this;\n },\n /** Reduce mod a modulus. Stubbed for subclassing. */\n reduce: function () {\n return this;\n },\n /** Reduce and normalize. */\n fullReduce: function () {\n return this.normalize();\n },\n /** Propagate carries. */\n normalize: function () {\n var carry = 0, i, pv = this.placeVal, ipv = this.ipv, l, m, limbs = this.limbs, ll = limbs.length, mask = this.radixMask;\n for (i = 0; i < ll || (carry !== 0 && carry !== -1); i++) {\n l = (limbs[i] || 0) + carry;\n m = limbs[i] = l & mask;\n carry = (l - m) * ipv;\n }\n if (carry === -1) {\n limbs[i - 1] -= pv;\n }\n this.trim();\n return this;\n },\n /** Constant-time normalize. Does not allocate additional space. */\n cnormalize: function () {\n var carry = 0, i, ipv = this.ipv, l, m, limbs = this.limbs, ll = limbs.length, mask = this.radixMask;\n for (i = 0; i < ll - 1; i++) {\n l = limbs[i] + carry;\n m = limbs[i] = l & mask;\n carry = (l - m) * ipv;\n }\n limbs[i] += carry;\n return this;\n },\n /** Serialize to a bit array */\n toBits: function (len) {\n this.fullReduce();\n len = len || this.exponent || this.bitLength();\n var i = Math.floor((len - 1) / 24), w = sjcl.bitArray, e = (len + 7 & -8) % this.radix || this.radix, out = [w.partial(e, this.getLimb(i))];\n for (i--; i >= 0; i--) {\n out = w.concat(out, [w.partial(Math.min(this.radix, len), this.getLimb(i))]);\n len -= this.radix;\n }\n return out;\n },\n /** Return the length in bits, rounded up to the nearest byte. */\n bitLength: function () {\n this.fullReduce();\n var out = this.radix * (this.limbs.length - 1), b = this.limbs[this.limbs.length - 1];\n for (; b; b >>>= 1) {\n out++;\n }\n return out + 7 & -8;\n }\n};\n/** @memberOf sjcl.bn\n* @this { sjcl.bn }\n*/\nsjcl.bn.fromBits = function (bits) {\n var Class = this, out = new Class(), words = [], w = sjcl.bitArray, t = this.prototype, l = Math.min(this.bitLength || 0x100000000, w.bitLength(bits)), e = l % t.radix || t.radix;\n words[0] = w.extract(bits, 0, e);\n for (; e < l; e += t.radix) {\n words.unshift(w.extract(bits, e, t.radix));\n }\n out.limbs = words;\n return out;\n};\nsjcl.bn.prototype.ipv = 1 / (sjcl.bn.prototype.placeVal = Math.pow(2, sjcl.bn.prototype.radix));\nsjcl.bn.prototype.radixMask = (1 << sjcl.bn.prototype.radix) - 1;\n/**\n * Creates a new subclass of bn, based on reduction modulo a pseudo-Mersenne prime,\n * i.e. a prime of the form 2^e + sum(a * 2^b),where the sum is negative and sparse.\n */\nsjcl.bn.pseudoMersennePrime = function (exponent, coeff) {\n /** @constructor\n * @private\n */\n function p(it) {\n this.initWith(it);\n /*if (this.limbs[this.modOffset]) {\n this.reduce();\n }*/\n }\n var ppr = p.prototype = new sjcl.bn(), i, tmp, mo;\n mo = ppr.modOffset = Math.ceil(tmp = exponent / ppr.radix);\n ppr.exponent = exponent;\n ppr.offset = [];\n ppr.factor = [];\n ppr.minOffset = mo;\n ppr.fullMask = 0;\n ppr.fullOffset = [];\n ppr.fullFactor = [];\n ppr.modulus = p.modulus = new sjcl.bn(Math.pow(2, exponent));\n ppr.fullMask = 0 | -Math.pow(2, exponent % ppr.radix);\n for (i = 0; i < coeff.length; i++) {\n ppr.offset[i] = Math.floor(coeff[i][0] / ppr.radix - tmp);\n ppr.fullOffset[i] = Math.floor(coeff[i][0] / ppr.radix) - mo + 1;\n ppr.factor[i] = coeff[i][1] * Math.pow(1 / 2, exponent - coeff[i][0] + ppr.offset[i] * ppr.radix);\n ppr.fullFactor[i] = coeff[i][1] * Math.pow(1 / 2, exponent - coeff[i][0] + ppr.fullOffset[i] * ppr.radix);\n ppr.modulus.addM(new sjcl.bn(Math.pow(2, coeff[i][0]) * coeff[i][1]));\n ppr.minOffset = Math.min(ppr.minOffset, -ppr.offset[i]); // conservative\n }\n ppr._class = p;\n ppr.modulus.cnormalize();\n /** Approximate reduction mod p. May leave a number which is negative or slightly larger than p.\n * @memberof sjcl.bn\n * @this { sjcl.bn }\n */\n ppr.reduce = function () {\n var i, k, l, mo = this.modOffset, limbs = this.limbs, off = this.offset, ol = this.offset.length, fac = this.factor, ll;\n i = this.minOffset;\n while (limbs.length > mo) {\n l = limbs.pop();\n ll = limbs.length;\n for (k = 0; k < ol; k++) {\n limbs[ll + off[k]] -= fac[k] * l;\n }\n i--;\n if (!i) {\n limbs.push(0);\n this.cnormalize();\n i = this.minOffset;\n }\n }\n this.cnormalize();\n return this;\n };\n /** @memberof sjcl.bn\n * @this { sjcl.bn }\n */\n ppr._strongReduce = (ppr.fullMask === -1) ? ppr.reduce : function () {\n var limbs = this.limbs, i = limbs.length - 1, k, l;\n this.reduce();\n if (i === this.modOffset - 1) {\n l = limbs[i] & this.fullMask;\n limbs[i] -= l;\n for (k = 0; k < this.fullOffset.length; k++) {\n limbs[i + this.fullOffset[k]] -= this.fullFactor[k] * l;\n }\n this.normalize();\n }\n };\n /** mostly constant-time, very expensive full reduction.\n * @memberof sjcl.bn\n * @this { sjcl.bn }\n */\n ppr.fullReduce = function () {\n var greater, i;\n // massively above the modulus, may be negative\n this._strongReduce();\n // less than twice the modulus, may be negative\n this.addM(this.modulus);\n this.addM(this.modulus);\n this.normalize();\n // probably 2-3x the modulus\n this._strongReduce();\n // less than the power of 2. still may be more than\n // the modulus\n // HACK: pad out to this length\n for (i = this.limbs.length; i < this.modOffset; i++) {\n this.limbs[i] = 0;\n }\n // constant-time subtract modulus\n greater = this.greaterEquals(this.modulus);\n for (i = 0; i < this.limbs.length; i++) {\n this.limbs[i] -= this.modulus.limbs[i] * greater;\n }\n this.cnormalize();\n return this;\n };\n /** @memberof sjcl.bn\n * @this { sjcl.bn }\n */\n ppr.inverse = function () {\n return (this.power(this.modulus.sub(2)));\n };\n p.fromBits = sjcl.bn.fromBits;\n return p;\n};\n// a small Mersenne prime\nvar sbp = sjcl.bn.pseudoMersennePrime;\nsjcl.bn.prime = {\n p127: sbp(127, [[0, -1]]),\n // Bernstein's prime for Curve25519\n p25519: sbp(255, [[0, -19]]),\n // Koblitz primes\n p192k: sbp(192, [[32, -1], [12, -1], [8, -1], [7, -1], [6, -1], [3, -1], [0, -1]]),\n p224k: sbp(224, [[32, -1], [12, -1], [11, -1], [9, -1], [7, -1], [4, -1], [1, -1], [0, -1]]),\n p256k: sbp(256, [[32, -1], [9, -1], [8, -1], [7, -1], [6, -1], [4, -1], [0, -1]]),\n // NIST primes\n p192: sbp(192, [[0, -1], [64, -1]]),\n p224: sbp(224, [[0, 1], [96, -1]]),\n p256: sbp(256, [[0, -1], [96, 1], [192, 1], [224, -1]]),\n p384: sbp(384, [[0, -1], [32, 1], [96, -1], [128, -1]]),\n p521: sbp(521, [[0, -1]])\n};\nsjcl.bn.random = function (modulus, paranoia) {\n if (typeof modulus !== \"object\") {\n modulus = new sjcl.bn(modulus);\n }\n var words, i, l = modulus.limbs.length, m = modulus.limbs[l - 1] + 1, out = new sjcl.bn();\n while (true) {\n // get a sequence whose first digits make sense\n do {\n words = sjcl.random.randomWords(l, paranoia);\n if (words[l - 1] < 0) {\n words[l - 1] += 0x100000000;\n }\n } while (Math.floor(words[l - 1] / m) === Math.floor(0x100000000 / m));\n words[l - 1] %= m;\n // mask off all the limbs\n for (i = 0; i < l - 1; i++) {\n words[i] &= modulus.radixMask;\n }\n // check the rest of the digitssj\n out.limbs = words;\n if (!out.greaterEquals(modulus)) {\n return out;\n }\n }\n};\n/** @fileOverview Bit array codec implementations.\n *\n * @author Marco Munizaga\n */\n//patch arraybuffers if they don't exist\nif (typeof (ArrayBuffer) === 'undefined') {\n (function (globals) {\n \"use strict\";\n globals.ArrayBuffer = function () { };\n globals.DataView = function () { };\n }(this));\n}\n/**\n * ArrayBuffer\n * @namespace\n */\nsjcl.codec.arrayBuffer = {\n /** Convert from a bitArray to an ArrayBuffer.\n * Will default to 8byte padding if padding is undefined*/\n fromBits: function (arr, padding, padding_count) {\n var out, i, ol, tmp, smallest;\n padding = padding == undefined ? true : padding;\n padding_count = padding_count || 8;\n if (arr.length === 0) {\n return new ArrayBuffer(0);\n }\n ol = sjcl.bitArray.bitLength(arr) / 8;\n //check to make sure the bitLength is divisible by 8, if it isn't \n //we can't do anything since arraybuffers work with bytes, not bits\n if (sjcl.bitArray.bitLength(arr) % 8 !== 0) {\n throw new sjcl.exception.invalid(\"Invalid bit size, must be divisble by 8 to fit in an arraybuffer correctly\");\n }\n if (padding && ol % padding_count !== 0) {\n ol += padding_count - (ol % padding_count);\n }\n //padded temp for easy copying\n tmp = new DataView(new ArrayBuffer(arr.length * 4));\n for (i = 0; i < arr.length; i++) {\n tmp.setUint32(i * 4, (arr[i] << 32)); //get rid of the higher bits\n }\n //now copy the final message if we are not going to 0 pad\n out = new DataView(new ArrayBuffer(ol));\n //save a step when the tmp and out bytelength are ===\n if (out.byteLength === tmp.byteLength) {\n return tmp.buffer;\n }\n smallest = tmp.byteLength < out.byteLength ? tmp.byteLength : out.byteLength;\n for (i = 0; i < smallest; i++) {\n out.setUint8(i, tmp.getUint8(i));\n }\n return out.buffer;\n },\n /** Convert from an ArrayBuffer to a bitArray. */\n toBits: function (buffer) {\n var i, out = [], len, inView, tmp;\n if (buffer.byteLength === 0) {\n return [];\n }\n inView = new DataView(buffer);\n len = inView.byteLength - inView.byteLength % 4;\n for (var i = 0; i < len; i += 4) {\n out.push(inView.getUint32(i));\n }\n if (inView.byteLength % 4 != 0) {\n tmp = new DataView(new ArrayBuffer(4));\n for (var i = 0, l = inView.byteLength % 4; i < l; i++) {\n //we want the data to the right, because partial slices off the starting bits\n tmp.setUint8(i + 4 - l, inView.getUint8(len + i)); // big-endian, \n }\n out.push(sjcl.bitArray.partial((inView.byteLength % 4) * 8, tmp.getUint32(0)));\n }\n return out;\n },\n /** Prints a hex output of the buffer contents, akin to hexdump **/\n hexDumpBuffer: function (buffer) {\n var stringBufferView = new DataView(buffer);\n var string = '';\n var pad = function (n, width) {\n n = n + '';\n return n.length >= width ? n : new Array(width - n.length + 1).join('0') + n;\n };\n for (var i = 0; i < stringBufferView.byteLength; i += 2) {\n if (i % 16 == 0)\n string += ('\\n' + (i).toString(16) + '\\t');\n string += (pad(stringBufferView.getUint16(i).toString(16), 4) + ' ');\n }\n if (typeof console === undefined) {\n console = console || { log: function () { } }; //fix for IE\n }\n console.log(string.toUpperCase());\n }\n};\nif (typeof module !== 'undefined' && module.exports) {\n module.exports = sjcl;\n}\nif (typeof define === \"function\") {\n define([], function () {\n return sjcl;\n });\n}\nexport default sjcl;\n", null, null, null, null, null, null, null, null, "import {\n AuthorizationHeader,\n IssuerConfig,\n MediaType,\n TOKEN_TYPES,\n Token,\n TokenChallenge,\n WWWAuthenticateHeader,\n header_to_token,\n publicVerif,\n util,\n} from \"@cloudflare/privacypass-ts\";\nimport * as asn1 from \"asn1js\";\n\nconst u8ToB64 = (u: Uint8Array): string => btoa(String.fromCharCode(...u));\n\nconst b64Tou8 = (b: string): Uint8Array =>\n Uint8Array.from(atob(b), (c) => c.charCodeAt(0));\n\nconst b64ToB64URL = (s: string): string =>\n s.replace(/\\+/g, \"-\").replace(/\\//g, \"_\");\n\nconst b64URLtoB64 = (s: string): string =>\n s.replace(/-/g, \"+\").replace(/_/g, \"/\");\n\nconst LOCAL_URL = window.origin;\nconst ECHO_URL = `${LOCAL_URL}/echo-authentication`;\nconst PROXY_URL = `${LOCAL_URL}/proxy`;\n\nconst SUPPORTED_TOKEN_TYPES = Object.values(TOKEN_TYPES).map(\n (tokenType) => tokenType.value,\n);\n\nclass TransformResult {\n private _string: string;\n private _fill: Record